gpt4 book ai didi

PHP MySQLi num_rows 总是返回 0

转载 作者:可可西里 更新时间:2023-11-01 07:03:52 25 4
gpt4 key购买 nike

我构建了一个类,它利用了 PHP 的内置 MySQLi 类的功能,旨在简化数据库交互。但是,使用 OOP 方法时,我很难使用 num_rows 实例变量在运行查询后返回正确的行数。看看我类(class)的快照......

class Database {
//Connect to the database, all goes well ...

//Run a basic query on the database
public function query($query) {
//Run a query on the database an make sure is executed successfully
try {
//$this->connection->query uses MySQLi's built-in query method, not this one
if ($result = $this->connection->query($query, MYSQLI_USE_RESULT)) {
return $result;
} else {
$error = debug_backtrace();

throw new Exception(/* A long error message is thrown here */);
}
} catch (Exception $e) {
$this->connection->close();

die($e->getMessage());
}
}

//More methods, nothing of interest ...
}

这是一个示例用法:

$db = new Database();
$result = $db->query("SELECT * FROM `pages`"); //Contains at least one entry
echo $result->num_rows; //Returns "0"
exit;

这怎么不准确?结果对象的其他值是准确的,例如“field_count”。

最佳答案

可能的错误:http://www.php.net/manual/en/mysqli-result.num-rows.php#104630

代码来自上面的源代码 (Johan Abildskov):

$sql = "valid select statement that yields results"; 
if($result = mysqli-connection->query($sql, MYSQLI_USE_RESULT))
{
echo $result->num_rows; //zero
while($row = $result->fetch_row())
{
echo $result->num_rows; //incrementing by one each time
}
echo $result->num_rows; // Finally the total count
}

也可以使用程序风格进行验证:

/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);

关于PHP MySQLi num_rows 总是返回 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6538891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com