Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Catching MYSQL errors

Status
Not open for further replies.

HughbertD

Technical User
Apr 30, 2007
42
GB
Hi all,

I want to be able to catch a "Cannot delete or update a parent row" error from a mysql database. Instead of just printing the error to the screen, I want to explain that some records need to be altered. Is there a way of doing this?

Thanks for any help
 
the error will be in the mysql_error() return. you can suppress the default message by prepending an @ to the mysql_query function
Code:
$result  = @mysql_query('somequery);
if (!$result){
 switch (mysql_error()){
   case "Cannot delete or update a parent row":
    echo "do something";
    break;
   default:
    echo mysql_error();
 }

it may be easier if you use the error codes rather than the error message.
 
I tried something similar to this, like

$error=substr(mysql_error(),0,10)
if ($error == "Cannot upda")
{
echo blah
}

But this did not work either. It just doesn't seem to echo anything onto the screen. I don't think that it is catching anything, does the error code come with mysql_error ?

I'm also unsure how to use break case statements.

Thanks if you can keep helping
 
personally i don' use foreign key constraints in mysql - i prefer to rely on programmatic logic and atomic transactions. but i see the point anyway.

as i cannot find the error message you refer to in the mysql manual, try checking for an error code betwen 1215 and 1217 (foreign key constraints).

Code:
$errorCode = mysql_errorno();
if ($errorCode <= 1215 && $errorCode >= 1217){
 echo "some message about constraints";
}
 
When I try mysql_errorno() I get call to undefined function.

Is there a built in function to get the errorno?
 
Ah its mysql_errno() however, I don't think the error falls within 1215-1217.
 
then find out what the error number is and capture that. as i said, i could not find anything in the mysql manual (for 5.0) that corresponded to the error message you reported.
 
Sorry, I already did this, after I stopped being lazy.

Thanks for the help!

(It was 1451)

:)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top