问题
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