PHP MySQLi num_行始终返回0
我已经构建了一个类,它利用了PHP内置MySQLi类的功能,旨在简化数据库交互。但是,使用OOP方法,我很难在运行查询后使用num_rows实例变量返回正确的行数。看一看我班级的快照PHP MySQLi num_行始终返回0,php,mysql,oop,mysqli,mysql-num-rows,Php,Mysql,Oop,Mysqli,Mysql Num Rows,我已经构建了一个类,它利用了PHP内置MySQLi类的功能,旨在简化数据库交互。但是,使用OOP方法,我很难在运行查询后使用num_rows实例变量返回正确的行数。看一看我班级的快照 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 da
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;
为什么这不准确?结果对象中的其他值是准确的,例如“字段计数”。非常感谢您的帮助
谢谢您的时间。可能的错误:
代码来自上面的源代码(Johan Abildskov):
还可以使用程序样式进行验证:
/* determine number of rows result set */
$row_cnt = mysqli_num_rows($result);
当您使用MYSQLI\u USE\u result禁用结果行的缓冲时,这可能是正常行为 禁用缓冲区意味着取回、存储和计数行由您决定。 您应该使用默认标志
$this->connection->query($query, MYSQLI_STORE_RESULT);
相当于
$this->connection->query($query)
我也有同样的问题,发现解决办法是:
$result->store_result();
..在执行$query之后和之前
echo$result->num_行 哎呀。。。这太容易了。谢谢你指出这一点。PHP站点的示例和我的示例查询都使用了“MYSQLI\u USE\u RESULT”常量。我去掉了它,它就像一个符咒!谢谢你的帮助,菲尔!请注意使用MYSQLI\u use\u RESULT:如果使用MYSQLI\u use\u RESULT,除非调用,否则所有后续调用都将返回不同步的错误命令
$result->store_result();