我正在编写以下代码来从表中获取一行:
$query = "SELECT ........FROM ............WHERE........AND ID = ?";
$conn = new Connection();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
echo 'Num rows = '.$stmt->num_rows();
这是Connection();
的代码define('SERVER', 'localhost');
define('USER', 'root');
define('PASS', 'xxx');
define('DB', 'xxx');
class Connection{
var $mysqli = null;
function __construct(){
try{
if(!$this->mysqli){
$this->mysqli = new MySQLi(SERVER, USER, PASS, DB);
if(!$this->mysqli)
throw new Exception('Could not create connection using MySQLi', 'NO_CONNECTION');
}
}
catch(Exception $ex){
echo "ERROR: ".$e->getMessage();
}
}
}
如果我回显查询并在ID等于$ _SESSION ['id']的值的Navicat上运行它,它确实会返回一行。但是在网页上,它显示输出为:
Num rows = 0
代码有什么问题? Plz注意 echo $ _SESSION ['id'] 显示值。
由于
答案 0 :(得分:1)
使用store_result()
存储结果集,然后访问$stmt->num_rows
作为属性,而不是方法。 (不要使用()
)
$query = "SELECT ........FROM ............WHERE........AND ID = ?";
$conn = new Connection();
$stmt = $conn->mysqli->prepare($query);
$stmt->bind_param('i', $_SESSION['id']);
$stmt->execute();
// Call store_result() before accessing num_rows()
$stmt->store_result();
// And access num_rows as a property, not a method
echo 'Num rows = '.$stmt->num_rows;