簡體   English   中英

PHP MySQLi num_rows 總是返回 0

[英]PHP MySQLi num_rows Always Returns 0

我構建了一個 class,它利用了 PHP 內置的 MySQLi class 的功能,旨在簡化數據庫交互。 但是,使用 OOP 方法,我很難讓 num_rows 實例變量在運行查詢后返回正確的行數。 看看我的 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;

這怎么不准確? 結果 object 中的其他值是准確的,例如“field_count”。 任何幫助是極大的贊賞。

感謝您的時間。

可能的錯誤: 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);

當您使用MYSQLI_USE_RESULT禁用結果行的緩沖時,這可能是正常行為

禁用緩沖區意味着您可以獲取、存儲和計數行。 您應該使用默認標志

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

相當於

$this->connection->query($query)

我遇到了同樣的問題,發現解決方案是:

$result->store_result();

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

回聲 $result->num_rows;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM