Homer_J
Homer_J

Reputation: 3323

Error in PHP using if() on a MYSQL result containing no rows

EDIT: Just to clarify, the query is correct - there are zero rows - the problem I am having is how to handle that in the PHP with the IF basically I am iterating through rows (10 of them) some will have some data for the query and some won't. The page falls over when a row doesn't. Does that make any sense?

I know I'm doing something inherently wrong and I am sure the solution is simple...

MySQL query brings back ZERO rows;

SELECT * from tresults WHERE date = 'MAY2012'

I then have some PHP code as follows:

if($row = mysql_fetch_array($result)){
    // do something
}

Now, as the query brings back ZERO rows, the page falls over on the IF statement...what am I doing wrong....

Upvotes: 2

Views: 157

Answers (2)

tofwiz
tofwiz

Reputation: 3

$result = mysql_query("SELECT * from tresults WHERE date = 'MAY2012'");

while ($row = mysql_fetch_array($result))
    {
        //do stuff;
    }

Upvotes: 0

SimonMayer
SimonMayer

Reputation: 4926

Check for the number of rows using mysql_num_rows()

if(mysql_num_rows($result) > 0){
  $row = mysql_fetch_array($result);
}

Or use while - note this will run for every row, if your query returns more than one row

while($row = mysql_fetch_array($result)){
  // do something
}

Upvotes: 2

Related Questions