num_rows:get_result与store_result [英] num_rows: get_result vs store_result

查看:84
本文介绍了num_rows:get_result与store_result的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使表类别中有cat = 1的表中有5个条目,以下代码也将返回0.

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;

但是,当我将$stmt->get_result();更改为$stmt->store_result();时,输出为5.为什么get_result()在这里不起作用?

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

例如,我在此答案上找到了一个例子: https://stackoverflow.com/a/8722329/2311074 c4>也应该起作用.

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

推荐答案

看起来其他答案是错误的,并且get_result不会更改语句的状态(这很合逻辑,因为您要的是mysqli_result,因此应该是从现在开始要使用它).

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).

您知道,使用get_result的方式是毫无意义的.要说明这一点,您必须将结果分配给变量,这将为您提供所需的结果:

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;

请注意,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!
}

当然,您不应仅使用此类查询来计算类别中的可用商品.为此,必须使用count(*)查询.

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.

这篇关于num_rows:get_result与store_result的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆