7

我构建了一个利用 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 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”。任何帮助是极大的赞赏。

感谢您的时间。

4

3 回答 3

5

可能的错误: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);
于 2011-06-30T18:00:15.643 回答
2

我遇到了同样的问题,发现解决方案是:

$result->store_result();

..在 $query 执行之后和之前

回声 $result->num_rows;

于 2018-12-06T10:59:42.277 回答
1

当您使用MYSQLI_USE_RESULT禁用结果行的缓冲时,这可能是正常行为

禁用缓冲区意味着您可以获取、存储和计数行。您应该使用默认标志

$this->connection->query($query, MYSQLI_STORE_RESULT); 

相当于

$this->connection->query($query)
于 2012-11-23T09:45:10.310 回答