为什么 store_result() 不返回 num_rows 等同于 mysqli 常规语句?

Why is store_result() not returning num_rows equivalent to mysqli Regular 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)) {(我知道这是错误的,并且来自旧语句)我的结果总是返回 li No 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();

它解决了我的问题并且一切正常。我知道有更好的方法可以做到这一点,所以如果有人有那个建议很好。与此同时,这将不得不做。