我能够从中获取数据get_result()
使用任何fetch_assoc()
, fetch_all()
, ..., 和fetch_row()
但是当我尝试使用简单的fetch()
只是,我收到这个错误
未捕获的错误:调用未定义的方法 mysqli_result::fetch()
这是因为使用get_result()
?或者我在下面的代码中遗漏了其他内容
$stmt = $conn->prepare($SQL);
$stmt->bind_param("s", $date);
$stmt->execute();
$result = $stmt->get_result();
//$row = $result->fetch_assoc();
//$row = $result->fetch_all();
//$row = $result->fetch_row();
$row = $result->fetch();
变量$stmt
是一个对象mysqli_stmt https://secure.php.net/manual/en/class.mysqli-stmt.php班级。这个类有一个方法叫做fetch() https://www.php.net/manual/en/mysqli-stmt.fetch.php它返回一个布尔值(真/假)。它仅与bind_result() https://www.php.net/manual/en/mysqli-stmt.bind-result.php
$stmt = $conn->prepare('SELECT myCol, myOtherCol FROM myTable WHERE dt=?');
$stmt->bind_param("s", $date);
$stmt->execute();
// The columns in SQL will be bound to the PHP variables
$stmt->bind_result($variable1, $variable2);
while ($stmt->fetch()) {
// This will fetch each record from the prepared statement one by one
printf ("myCol is %s and myOtherCol is %s\n", $variable1, $variable1);
}
$stmt->get_result() https://www.php.net/manual/en/mysqli-stmt.get-result.php返回一个类的对象mysqli_result https://www.php.net/manual/en/class.mysqli-result.php(顺便说一下,可以使用foreach
)。这个类有不同的方法,但它没有fetch()
method.
-
fetch_all() https://www.php.net/manual/en/mysqli-result.fetch-all.php返回一个数组的数组。顾名思义,它会立即返回结果集中的所有记录。
$result = $stmt->get_result();
$allRecords = $result->fetch_all(\MYSQLI_ASSOC);
echo json_encode($allRecords);
-
fetch_array() https://www.php.net/manual/en/mysqli-result.fetch-array.php将每条记录一一返回为一维数组
$row = $result->fetch_array();
printf("%s (%s)\n", $row["myCol"], $row["myOtherCol"]);
-
fetch_assoc() https://www.php.net/manual/en/mysqli-result.fetch-assoc.php相当于
fetch_array(\MYSQLI_ASSOC)
-
fetch_row() https://www.php.net/manual/en/mysqli-result.fetch-row.php相当于
fetch_array(\MYSQLI_NUM)
-
fetch_object() https://www.php.net/manual/en/mysqli-result.fetch-object.php将每条记录作为对象一一返回。
$row = $result->fetch_object();
printf("%s (%s)\n", $row->myCol, $row->myOtherCol);
但是,为了简单起见,您可以循环mysqli_result
直接将每一行作为关联数组。
foreach($stmt->get_result() as $row) {
printf("%s (%s)\n", $row["myCol"], $row["myOtherCol"]);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)