在fetch_array之后获取num_rows的正确命令顺序(mysqli OOP) [英] Proper command order to get num_rows after fetch_array (mysqli OOP)
问题描述
以数组形式获取结果时遇到num_row
的问题:
I'm having a problem getting a num_row
when I fetch the results as an array:
$sql = "SELECT * FROM people WHERE peopleid=?";
if (!($stmt = $mysqli->prepare($sql))) {
echo "stmt Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$stmt->bind_param("i", $_GET['peopleid'])) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$stmt->store_result();
$exist=$stmt->num_rows;
$result = $stmt->get_result();
$peopleres = $result->fetch_array(MYSQLI_ASSOC); // this does work :)
if ($exist == 0) {
//do something it it's zero
}
如果在示例中将store_results和num_rows放在其中,则会得到
If I place the store_results and num_rows where it is in the example I get an
在发生非对象错误时调用成员函数fetch_array().
Call to a member function fetch_array() on a non-object error.
如果我将其放置在fetch_array之后,它将始终等于零.我以前曾经成功使用过num_rows,但这是我第一次尝试与fetch_array一起使用.
If I place it after the fetch_array it's always equal to zero. I've used num_rows successfully before, but this is the first time I'm trying to use it alongside a fetch_array.
推荐答案
看一下文档
mysqli_result :: $ num_rows
int $mysqli_result->num_rows;
mysqli_result::$num_rows
int $mysqli_result->num_rows;
如果出于某些原因,请使用num_rows
代替
If you want for some reason use num_rows
instead of
$stmt->store_result();
$exist=$stmt->num_rows;
$result = $stmt->get_result();
$peopleres = $result->fetch_array(MYSQLI_ASSOC); // this does work :)
if ($exist == 0) {
//do something it it's zero
}
您可以尝试
$result = $stmt->get_result();
$exist = $result->num_rows;
if ($exist == 0) {
//do something it it's zero
}
$row = $result->fetch_array(MYSQLI_ASSOC);
现在,如果您只是检查结果集中是否有任何行,那么使用num_rows
并不是绝对必要的,因为您已经在客户端上获得了结果集.您可以尝试获取一行
Now if you're just checking whether you have any rows in the resultset or not the usage of num_rows
is not absolutely necessary since you already get your resultset on the client. You can just try to fetch a row
$result = $stmt->get_result();
if (!$row = $result->fetch_array(MYSQLI_ASSOC)) {
//do something if there's no row
} else {
//do what you have to do with you data in the row
echo 'peopleid: ' . $row['peopleid'];
}
这篇关于在fetch_array之后获取num_rows的正确命令顺序(mysqli OOP)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!