1

Using php I understand that false is the same as 0, so when checking my select query results, if I have 0 results mysql_num_rows($result) will evaluate to false - this i understand, what will the function evaluate to if I have an sql error.

$sqlQuery="SELECT userID, userName, password, role From User WHERE userName=$userName;"
$result=mysql_query($sqlQuery);
if(mysql_num_rows($result)){
    #I have results so process
} else #do I have an error or do I just have no results

I need to return a meaningful result from the query i.e. "no such user" or details of the sql error, I do not wish to use mysql_query($sqlQuery) or die(). I have searched the web and can't find a conclusive answer. Any help would be greatly appreciated.

Amanda

Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
Amanda
  • 11
  • 1
  • 2

5 Answers5

2

You can check using ===

if(($result = mysql_query('select * from foo')) === false) {
   // mysql error
} else {
   if(mysql_num_rows($result) == 0) echo 'no such user.';
}

or if you just want to modify your code, you could go with:

$sqlQuery="SELECT userID, userName, password, role From User WHERE userName=$userName;"
$result=mysql_query($sqlQuery);
if(mysql_num_rows($result)){
    #I have results so process
} else {
    #do I have an error 
    if($result === false) {
        // mysql error indeed

    #or do I just have no results
    } else { 
        echo 'no such user';
    }
}
Andreas Wong
  • 59,630
  • 19
  • 106
  • 123
1
$res=mysql_query('smth');
if(mysql_error()){//error
}
else{//correct, you can check mysql_num_rows
}
RiaD
  • 46,822
  • 11
  • 79
  • 123
1

mysql_query() will return false on error, and the result resource otherwise. mysql_num_rows() will throw a warning if you send it false, so you need to determine if the query worked anyway

$result = mysql_query($query);
if ($result === false) {
   //handle error
}
else if (mysql_num_rows($result)) {
   //handle rows
}
else {
   //handle no rows
}
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
0
if(mysql_num_rows($result) != 0){
    #I have results so process
} else{ 
    echo 'No such user';
}
Warface
  • 5,029
  • 9
  • 56
  • 82
0

You can use PHP's typed comparison operators to differentiate between 0 and false. So your test would become:

$num_rows = mysql_num_rows($result);
if($num_rows > 0){
    #I have results so process
} else if ($num_rows === false) {
    #An error occured: use mysql_error for details
} else {
    #No errors, no results either
}