我试图计算结果中的行数,并且我一直收到上面返回的错误。我已经检查了手册,并且我正在使用mysqli_result :: num_rows(),因为我应该这样做(我使用面向对象的风格。)我在这里工作了三节课。 / p>
班级(连接):
class utils_MysqlImprovedConnection {
protected $_connection;
public function __construct($host, $user, $pwd, $db)
{
$this->_connection = @new mysqli($host, $user, $pwd, $db);
if(mysqli_connect_errno ()) {
throw new RuntimeException('Cannot access database:' . mysqli_connect_error());
}
}
public function getResultSet($sql)
{
$results = new utils_MysqlImprovedResult($sql, $this->_connection);
return $results;
}
public function __destruct() {
$this->_connection;
}
}
类(处理结果):
class utils_MysqlImprovedResult implements Iterator, Countable {
protected $_key;
protected $_current;
protected $_valid;
protected $_result;
public function __construct($sql, $connection) {
if (!$this->_result = $connection->query($sql)){
throw new RuntimeException($connection->error . '. The actual query submitted was: '. $sql);
}
}
public function rewind()
{
if (!is_null($this->_key)){
$this->_result->data_seek(0);
}
$this->_current = $this->_result->fetch_assoc();
$this->_valid = is_null($this->_current) ? false : true;
}
public function valid()
{
return $this->_valid;
}
public function current()
{
return $this->_current;
}
public function key()
{
return $this->_key;
}
public function next()
{
$this->_current = $this->_result->fetch_assoc();
$this->_valid = is_null($this->_current) ? false : true;
$this->_key++;
}
public function count()
{
$this->_result->store_result();
$this->_result->num_rows();
}
}
班级职能:
public function resetPassword($email, $pass){
//check if email exists, update authkey and password, send email
$sql = "SELECT * FROM table WHERE column = '$email'";
$results = $this->_db->getResultSet($sql);
if($results->count() == 1){
// Process
$this->_message = "Success!";
return $this->_message;
} else {
// Not unique
$this->_error = "Try again";
return $this->_error;
}
}
我用来调用所有这些的测试页面是(include语句只是__autoload()函数正常工作):
$columnvar = 'emailaddress@test.com';
$pass = 'blah';
require_once 'inc.init.php';
$user = new utils_User();
try{
$string = $user->resetPassword($email, $pass);
echo $string;
}
catch(Exception $e) {
echo $e;
}
答案 0 :(得分:8)
从手册中,mysqli_result::num_rows似乎不是一个函数,而是一个包含行数的变量。
可以像这样使用:
$num_rows = $mysqli_result->num_rows;
等效函数是mysqli_num_rows($result)
,您传入mysqli_result
对象,但是如果您使用的是过程样式而不是面向对象样式。
在您的代码中,您应该将count()
类中的utils_MysqlImprovedResult
函数更改为(我假设这是您收到错误消息的函数),
public function count()
{
// Any other processing you want
// ...
return $this->_result->num_rows;
}
或者如果你想混合OO和程序风格(可能是一个坏主意),
public function count()
{
// Any other processing you want
// ...
return mysqli_num_rows($this->_result);
}