mysql 中的 store_result() 和 get_result() 返回 false

2021-12-25 00:00:00 php mysqli prepared-statement

几天前我做了一个代码,包括 get_result() 来从我的数据库中接收结果.今天我想添加它并修复一些错误.所以我尝试使用 num_rows 来查看是否有任何返回.但为此我不得不使用 store_result().当我这样做时,get_result() 只返回一个布尔值 false.当我注释掉 store_result() 时,一切正常.我知道 >= 会搞砸.但我把 = 放在那里进行调试(注释掉 store_result() 并查看发生了什么).所以这不是问题

I made a code a few days ago including get_result() to receave the results from my database. Today I wantet to add to it and fix some errors. So I tried to use num_rows to see if anything were returned. But for this I had to use store_result(). And when I do this get_result() just returns a boolean of false. When I comment out store_result() everything works as it should. I know that the >= will mess it up. But I put the = there for debugging(to comment out the store_result() and see what happend). So that is not the problem

$sql = $this->connect();
$a = $sql->prepare("SELECT `name`, `title`, `comment`, `date`  FROM `comment` WHERE `post`=?");
$a->bind_param("s", $id);
$a->execute();
$a->store_result();
if ($a->num_rows >= 0) {
    $res = $a->get_result();
    var_dump($res);

    while ($row = $res->fetch_assoc()) {
        $results[] = $row;
    }
    return $results;
} else {
    return false;
}

推荐答案

使用 get_result() 代替 store_result(),然后使用结果对象的 num_rows:

Use get_result() instead of store_result(), and then use the result object's num_rows:

$a->execute();
$res = $a->get_result();
if ($res->num_rows > 0) {
    while ($row = $res->fetch_assoc()) {
        $results[] = $row;
    }
    return $results;
} else {
    return false;
}

相关文章