PHP MySQLi num_rows始终返回0 [英] PHP MySQLi num_rows Always Returns 0

查看:259
本文介绍了PHP MySQLi num_rows始终返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建立了一个利用PHP内置MySQLi类功能的类,该类旨在简化数据库交互.但是,使用OOP方法时,num_rows实例变量在运行查询后返回正确的行数时遇到了麻烦.看看我班级的快照...

I have built a class which leverages the abilities of PHP's built-in MySQLi class, and it is intended to simplify database interaction. However, using an OOP approach, I am having a difficult time with the num_rows instance variable returning the correct number of rows after a query is run. Take a look at a snapshot of my 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".任何帮助,我们将不胜感激.

How come this is not accurate? Other values from result object are accurate, such as "field_count". Any help is greatly appreciated.

谢谢您的时间.

推荐答案

可能的错误:代码来自上述来源(约翰·阿比兹科夫):

Code is from source above (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 
}

也可以使用程序样式进行验证:

Could also validate with the Procedural style:

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

这篇关于PHP MySQLi num_rows始终返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆