Giving user-friendly error messages for database errors

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
hannahd
Forum Newbie
Posts: 16
Joined: Wed Feb 18, 2004 9:40 am

Giving user-friendly error messages for database errors

Post by hannahd »

Hello,

I am using MySQL and PHP and I want to give a user-friendly error message when somebody tries to enter a duplicate record.

So instead of Duplicate entry ' ' for key 2, I want it to say something like ' this record has already been entered'.

Is there a way of writing user-friendly messages by seeing what kind of error occured or is the only way to do a select query on the database to see if the record exists. I don't want to do that if there's a better, less costly way of doing it.

Thanks

Hannah
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

Probably best to execute a query to check to see if the value is already in the table before you execute your INSERT statement.

Some pseudo code

Code: Select all

// Query to check for existing data

if (data_already_exists) {
    print "This data already exists in the DB";
} else {
   // INSERT data into the DB
}
Mark
hannahd
Forum Newbie
Posts: 16
Joined: Wed Feb 18, 2004 9:40 am

Post by hannahd »

Thanks :)

But are you sure there isn't a more efficient way of doing it?
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

you could do iot in one query, but it isn't very flexible

Code: Select all

$result = mysql_query($query) or die ("this record has already been entered");
If the Query failed, it would output "this record has already been entered".

This would be just plain text, not formatted, and the message would occur even if the error wasn't with duplicate info, if would display the same message for ALL error on that query.

I would go with my first option, for more flexible.

Mark
hannahd
Forum Newbie
Posts: 16
Joined: Wed Feb 18, 2004 9:40 am

Post by hannahd »

That's what I thought. I have decided to go along with what you said.

Thanks for your help. :)
User avatar
AVATAr
Forum Regular
Posts: 524
Joined: Tue Jul 16, 2002 4:19 pm
Location: Uruguay -- Montevideo
Contact:

Post by AVATAr »

the problem with die ("this record has already been entered"); approach is that you break the html code and you could have problems with navigation.. i do prefer the if else approach...
Post Reply