Best way to know if select statement returned rows

I am using


while($row = mysql_fetch_array($rs)){
		$id = $row['id'];
		// etc....		
	}

What is the best way to know if my SELECT statement returned rows? I read before that using mysql_num_rows($rs) can be unreliable in certain situations. Is that true?

If mysql_num_rows can be unreliable is it bad to reverse a boolean only if the while loop is entered and check the variable after the while:


$hasRows = false;
while($row = mysql_fetch_array($rs)){
               $hasRows = true;
		$id = $row['id'];
		// etc....		
	}
if(!$hasRows){
       // there were no rows..
}

Thanks for pointing that out, changed it :slight_smile:

aaronbd the connection method you explain uses a procedural method, it should be

$conn = new mysqli('localhost', 'username', 'password','database') or die ('Could not connect to the database.');

If you are interested in doing it in OO:


<?php

$conn = new mysqli('localhost', 'username', 'password','database')
or die ('Could not connect to the database.');

$result = $conn->query("select * from table");

if ($result->num_rows>0) {

     while($row = $result->fetch_assoc()){
            $id = $row['id'];
  } else {
     throw new Exception('Did not find any results.');
  }

?>

Hope this helps!

In my experience mysql_num_rows has done its correct job and has worked perfect no matter what for me. I’ve used for everything from INNER JOIN to LEFT JOIN and it has returned an accurate number.

Basically what i do is this…

if (mysql_num_rows($rs) > 0){
    while($row = mysql_fetch_row($rs)){
        
    }
} else {
    echo 'No results in the database!';
}