Help - Search - Members - Calendar
Full Version: mySQL Query Question
Invision Power Services > Community Forums > Community Web Design and Coding
SnakEyez
Let me get right to the point. What I have is a query that searches if a row exists and if it doesn't I don't want the script to execute. Originally I thought I could just use something like:

("SELECT * FROM whatever WHERE this=that") or die("Error Message");

However, I ran into a problem that I didn't expect. The thing is when I use die(mysql_error()) it reports a "Resource ID #4" for the query because the query returns nothing. However, when I don't use the mySQL error then it ignores the die command. I tried running some other sample commands in phpMyAdmin trying to figure this out and I can't figure out how to tell the query to return a null or false value if there is no result to return. I mean I am assuming the reason the die command isn't working is because there is nothing wrong with the query because technically speaking the query just returns 0 results.

Now I realize I could probably just use another if statement using mysql_num_rows to figure out if anything was returned, but I am more curious to find out if there is a way to do this within the mySQL query statement that would return something useful so that I could break the if statement and possibly display my own error message instead of the mysql resource id one.
Chroder
So you want the query to return false so it will trigger the die()? I don't think you can do that. The select query will return a result set on success (even if it is an empty result set) or false on error. I don't think you can tell mySQL to give itself an error if it finds an empty result set.

Why not just create a custom function that does it all for you?

CODE
function noRowError($sql, $msg)
{
   $res = mysql_query($sql);

   if(!$res || mysql_num_rows($res) < 1)
       die($msg);
}


If you need to use the result set if it isn't empty, you can make a function that sets the result to false:

CODE
$result = noRowError("SELECT * FROM whatever WHERE this=that") or die("Error Message");

function noRowError($sql)
{
   $res = mysql_query($sql);

   if(!$res || mysql_num_rows($res) < 1)
       $res = false;

   return $res;
}
Brendon Koz
There's absolutely no reason for it to ignore the die() command call... I use it ALL the time without mysql_error or mysql_errno. These functions are only supposed to be used for debugging, in a real environment, you'd want to handle errors gracefully.

Anyway, try the following:

CODE
$sql = 'SELECT * FROM whatever WHERE this=that';
$result = mysql_query($sql);
if(!$result){
   die($err_msg);
}
//else, continue...


HTH
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2009 Invision Power Services, Inc.