Saurabh
Saurabh

Reputation: 139

How to Simplify MySQL Error Before Displaying it in PHP?

Suppose you have a table 'Store' with a column 'domain' which is unique. Adding duplicate entry will generate error such as:
Fatal error: Wrong SQL:INSERT INTO store (name, domain, alias, comment) VALUES ('Flipkart', 'www.flipkart.com', 'NA', 'Good Store') Error:Duplicate entry 'www.flipkart.com-' for key 'domain' in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\MyProj\Store.php on line 21

But, to common user, I want to simply display it as:

Duplicate Entry Detected. Try Again..!

One way is to first search for duplicate entry programmatically. And then try to insert it only if such entry is not found in table.
But, is there any way to do this more easily (without making any extra SQL query)?

Upvotes: 1

Views: 164

Answers (2)

Mohammad
Mohammad

Reputation: 3547

MySQL returns an error in the form of a number, a state, and a message.

So you need to catch the error code number and then use it like this:

if(mysqli_errno($db_connection)==1062){

    echo "Duplicate Entry Detected. Try Again..!";
}

Upvotes: 0

Matt
Matt

Reputation: 2869

Check mysql_errno or mysqli_errno and see if the error code is 1062 or MYSQL_CODE_DUPLICATE_KEY like so:

if(mysqli_errno($connection) == 1062)
{
//The query failed due to duplicate keys.
}

Then suppress the warning in your production server.

Upvotes: 2

Related Questions