Proper command order to get num_rows after fetch_array (mysqli OOP)

南笙酒味 提交于 2020-01-03 06:39:15

问题


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
}

If I place the store_results and num_rows where it is in the example I get an

Call to a member function fetch_array() on a non-object error.

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.


回答1:


Take a look at the documentation

mysqli_result::$num_rows
int $mysqli_result->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
}

you may try

$result = $stmt->get_result();
$exist = $result->num_rows;
if ($exist == 0) {
    //do something it it's zero
}
$row = $result->fetch_array(MYSQLI_ASSOC);

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'];
}



回答2:


num rows is a most useless function ever.
And you don't need it either. Just fetch your data and use it instead of $exists flag:

if(!$peopleres) ...



回答3:


You can also use :

$exist = $stmt->affected_rows;

remove :

$stmt->store_result();
$exist=$stmt->num_rows;
$result = $stmt->get_result();

add : $result = $stmt->get_result(); $exist = $stmt->affected_rows;



来源:https://stackoverflow.com/questions/20727608/proper-command-order-to-get-num-rows-after-fetch-array-mysqli-oop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!