为什么store_result()不返回等同于mysqli Regular Statement的num_rows



我一直在梳理以前的问题,并尝试了许多解决方案,但无法解决这个问题。我正在尝试将此查询转换为Prepared Statement:

$query = mysqli_query($this->con, "SELECT * FROM notifications WHERE user_to='$userLoggedIn' ORDER BY id DESC");

这是我所拥有的:

$query = $this->con->stmt_init();
$query->prepare('SELECT * FROM notifications WHERE user_to=? ORDER BY id DESC');
$query->bind_param('s', $userLoggedIn);
$query->execute();
$query->store_result();
$qty = $query->num_rows;
$query_result = $query->get_result();

在这个代码下面,我有这样使用的变量:

if($qty == 0) {
echo "<li class='no-more-posts' style='height: 0px; text-transform: uppercase;'>- You have no notifications! -</li>";
return;
}
$num_iterations = 0; //Number of messages checked 
$count = 1; //Number of messages posted
while($row = $query_result->fetch_assoc()) {
if($num_iterations++ < $start)
continue;
if($count > $limit)
break;
else 
$count++;
$user_from = $row['user_from'];
etc.etc.

我得到的是下拉列表中的空白结果。如果我将while语句改回原来的while($row = mysqli_fetch_array($query)) {(我知道这是错误的,而且是旧语句(,我的结果总是返回liNo More Posts to Show。这告诉我$qty = $query->num_rows;正在返回0。根据文档,我的理解是,一旦我用store_result()缓冲了结果集,我就可以立即调用$qty = $query->num_rows;。我在这里错过了什么?

我确信这不是最有效的做事方式,但这是我的全部;决定打破这个说法。

首先,我为计数做了一个声明:

$query_count = $this->con->stmt_init();
$query_count->prepare('SELECT COUNT(*) FROM notifications WHERE user_to=?');
$query_count->bind_param('s', $userLoggedIn);
$query_count->execute();
$query_count_result = $query_count->get_result();
$rows_count = $query_count_result->fetch_array();
$qty = array_shift($rows_count);

然后我为数据做了一个声明:

$query = $this->con->stmt_init();
$query->prepare('SELECT * FROM notifications WHERE user_to=? ORDER BY id DESC');
$query->bind_param('s', $userLoggedIn);
$query->execute();
$query_result = $query->get_result();

它解决了我的问题&一切如预期。我知道有更好的方法可以做到这一点,所以如果有人有这个建议,那就太好了。在此期间,这将不得不做。

最新更新