Php 行数:获取结果与存储结果
下面的代码返回0,即使表categories中有5个条目Php 行数:获取结果与存储结果,php,mysqli,prepared-statement,Php,Mysqli,Prepared Statement,下面的代码返回0,即使表categories中有5个条目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_r
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\u result()
在这里不起作用
例如,我在这个答案上发现:get_result()
也应该可以工作。看起来另一个答案是错误的,get_result不会改变语句的状态(这是非常合乎逻辑的,因为您要求的是mysqli_result,因此从现在开始就应该使用它)
你看,你使用get_result的方式是毫无意义的。要强调这一点,您必须将结果分配给一个变量,该变量将为您提供所需的结果:
$res = $stmt->get_result();
echo $res->num_rows;
请注意,num_rows属性通常是无用的。如果您想知道查询是否返回任何数据,只需将行收集到数组中,然后使用此数组即可
$data = $stmt->get_result()->fetch_all();
if ($data) {
// whatever
} else {
// oops!
}
当然,您不应该只使用这样的查询来统计某个类别中的可用商品。为此,必须使用count(*)
查询。看起来另一个答案是错误的,并且get\u result不会改变语句的状态(这是非常合乎逻辑的,因为您需要mysqli\u result,因此从现在开始应该使用它)
你看,你使用get_result的方式是毫无意义的。要强调这一点,您必须将结果分配给一个变量,该变量将为您提供所需的结果:
$res = $stmt->get_result();
echo $res->num_rows;
请注意,num_rows属性通常是无用的。如果您想知道查询是否返回任何数据,只需将行收集到数组中,然后使用此数组即可
$data = $stmt->get_result()->fetch_all();
if ($data) {
// whatever
} else {
// oops!
}
当然,您不应该只使用这样的查询来统计某个类别中的可用商品。为此,必须使用count(*)
查询