cds5059
cds5059

Reputation: 125

Catching mysql_query error

I am trying to stop the mysql_query error from being output onto my form. Currently if there is no location found, I receive the error

"Warning: mysql_result() [function.mysql-result]: Unable to jump to row 0 on MySQL result index 11"

I am trying to catch this error, and instead assign the $location variable to not found. My code for attempting this is below, what am I doing wrong?

Thanks!

$query3 = "SELECT `location` FROM location WHERE vin = '$vin' LIMIT 1";
$result3 = mysql_query($query3);

if (!mysql_result($result3,0)) {
    $location = "Not found";
} else $location = mysql_result($result3,0,0);

Upvotes: 6

Views: 27908

Answers (5)

artyom.stv
artyom.stv

Reputation: 2164

First, you can add @:

if (!@mysql_result($result3,0)) {
    $location = "Not found";
} else $location = mysql_result($result3,0,0);

Second, you can check mysql_num_rows(result3) before mysql_result call.

Upvotes: 0

Yahel
Yahel

Reputation: 8550

Mysql_query returns false if nothing is found so a simple :

$result3 = mysql_query($query3);

if (mysql_affected_rows($result3) == 0) {
    $location = "Not found";
} else  $location = mysql_result($result3,0,0);

Should do it.

Upvotes: -1

Marc B
Marc B

Reputation: 360572

mysql_result() generally shouldn't be used. You'd be better off with something like:

$result3 = mysql_query($query3) or die(mysql_error());

if (mysql_numrows($result3) == 0) then
   $location = "not found";
} else {
   $row = mysql_fetch_array($result3);
   $location = $row[0];
}

Your error is caused by the fact that the query returned no rows - e.g. nothing matched. You then tried to retrieve the first field in the first row of that result set, a row which doesn't exist. Checking the number of returned rows with mysql_numrows() is safer, as that works whether the query found nothing or a bajillion rows.

Upvotes: 8

tcarter2005
tcarter2005

Reputation: 617

You should look into using OOP; using a database class to handle interaction with your DB.

But, basically you want to check if there are any rows, before trying to bring back the results.

Try checking with "mysql_num_rows" in your "if" statement:

if (!mysql_num_rows($result3)) {

Upvotes: 0

picus
picus

Reputation: 1537

You should look into how to set your error and warning levels in php ini - usually you want a s little output on prod as possible.

http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting

However, here, the code that would generate that error is:

$result3 = mysql_query($query3);

That is the line you should be writing your if or "or die" statements around:

$result3 = mysql_query($query3)or die($location = "not found");

Upvotes: 0

Related Questions