Jump to content

mysql_error() and foreign Key


siezma

Recommended Posts

Hello,
I have a question about foreign key issues.When i try to delete one record in the database(which has some related record in another table - foreign key).The script shows an error message(coming from mysql_error()).The content of the message is below;

"Cannot delete or update a parent row: a foreign key constraint fails "

What i want to do is to analyze the error and show more user friendly messages such as
"you can't delete this record,because there are some related records etc.. "

How can i do that with php? I wonder how other programmers handle this issue with php?

Thanks
Link to comment
Share on other sites

You could do something like:

[code]
$err_num = mysql_errno();
if( $err_num == 1217 ) // the number of the error you specified
{
  echo "you can't delete this record, because there are some related records etc..";
}
[/code]

You can find a list of error codes at [url=http://dev.mysql.com/doc/refman/5.0/en/error-handling.html]http://dev.mysql.com/doc/refman/5.0/en/error-handling.html[/url]

Also, if the query automatically echos errors (can't remember off the top of my head) you could prefix it with an @.

Another technique might be to create an array of strings of the form

$friendlySqlErr[1217] = "you can't delete this record, because there are some related records etc..";

possibly as a reusable library? Then have something like

[code]
$err_num = mysql_errno();
if( isset( $friendlySqlErr[$err_num] )
{
  echo $friendlySqlErr[$err_num];
}
else
{
  echo mysql_error();
}
[/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.