PHP MySQLi num_rows Always Returns 0

19,139

Solution 1

Possible Bug: http://www.php.net/manual/en/mysqli-result.num-rows.php#104630

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);

Solution 2

I had the same problem and found the solution was to put:

$result->store_result();

..after the execution of the $query and before

echo $result->num_rows;

Solution 3

This could be normal behavior when you disable buffering of the result rows with MYSQLI_USE_RESULT

Disabling the buffer means that it`s up to you to fetch, store and COUNT the rows. You should use the default flag

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

Equivalent of

$this->connection->query($query)
Share:
19,139
Oliver Spryn
Author by

Oliver Spryn

My first programming experience was a trial-by-fire adventure. It wasn't a "Hello World" application but a full-fledged, web-based learning management system. This exposure galvanized my career choice and prepared me to face a myriad of challenges head-on. My unconventional start continues to yield tangible successes in nearly every discipline I touch, whether on the technical, operational, or business level. Since then, I've been on a mission to make technology work seamlessly and feel invisible. I have delivered this continued success with a daily, sleeves-rolled-up approach. Whenever my superiors need their most complex projects to be built and flawlessly delivered, they ask my team. I keep a good rapport with my colleges and managers so that working as a team is flawless. Their confidence in me has enabled me to be at the forefront of the engineering and design efforts necessary to bring applications from 0 to over 600k users. Building projects of this quality becomes a craft. The concepts I've worked to develop, discover, and distill have worked so well that they have been featured on the droidcon blog, home of Europe's foremost Android conference. Whether my work is published on a prominent blog or neatly packed inside of some back-end service, I ensure that I conduct each of these projects with my full measure of integrity. This trait is essential in delivering healthy projects on time, and it sets the good projects apart from the great ones. Prominent Skills: Android, Kotlin, Gradle, Azure Media Services, Azure Functions, Cloudflare Workers, Adobe Premiere Pro, Adobe Illustrator, All Forms of Communication, Videography, Listening, Critical Thinking

Updated on June 14, 2022

Comments

  • Oliver Spryn
    Oliver Spryn almost 2 years

    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 ...
    }
    

    Here is a sample usage:

    $db = new Database();
    $result = $db->query("SELECT * FROM `pages`"); //Contains at least one entry
    echo $result->num_rows; //Returns "0"
    exit;
    

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

    Thank you for your time.

  • Oliver Spryn
    Oliver Spryn almost 13 years
    Gahh... It was so easy. Thanks for pointing that out. Both the PHP site's example and my example queries were using the "MYSQLI_USE_RESULT" constant. I removed that and it works like a charm! Thanks for your help, Phil!
  • Kevin Cittadini
    Kevin Cittadini about 10 years
    Just a note for use of MYSQLI_USE_RESULT: PHP mysql::query If you use MYSQLI_USE_RESULT all subsequent calls will return error Commands out of sync unless you call mysqli_free_result()