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
https://forums.phpfreaks.com/topic/25648-mysql_error-and-foreign-key/
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]

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.