num_rows: get_result vs store_result

纵然是瞬间 提交于 2019-12-20 04:28:19

问题


The following code returns 0, even though there are 5 entries in the table categories with cat = 1.

$sql = "SELECT name FROM categories WHERE cat = ?";
$stmt = $db->prepare($sql);
$cat = 1;
$stmt->bind_param("i", $cat);
$stmt->execute();
$stmt->get_result();
echo $stmt->num_rows;

However, when I change $stmt->get_result(); to $stmt->store_result(); the output is 5. Why does get_result() not work here?

I found for instance on this answer: https://stackoverflow.com/a/8722329/2311074 that get_result() should also work.


回答1:


Looks like the other answer is wrong and get_result doesn't change the state of a statement (which is quite logical, as you are asking for mysqli_result and therefore supposedly going to work with it from now on).

You see, the way you are using get_result is quite pointless. To make any point of it, you have to assign the result to a variable, which will give you the desired outcome:

$res = $stmt->get_result();
echo $res->num_rows;

Note that the num_rows property is quite useless in general. If you want to know whether your query returned any data or not, just collect the rows into array and then you use this array for the purpose.

$data = $stmt->get_result()->fetch_all();
if ($data) {
    // whatever
} else {
    // oops!
}

And of course you shouldn't use such a query only to count the goods available in a category. For such a purpose a count(*) query have to be used.



来源:https://stackoverflow.com/questions/40192229/num-rows-get-result-vs-store-result

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