php duplicate key message?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
adilmarwat2004
Forum Commoner
Posts: 44
Joined: Fri Sep 04, 2009 11:28 pm

php duplicate key message?

Post by adilmarwat2004 »

I have table in mysql name "merit" contains 4 fields named "roll", "name", "father_name", "domicile".

How i code that when ever i enter the duplicate value in the "roll" coloumn of the table which mentioning message like
"You Enter Duplicate Values".

please help.

Adil
mikosiko
Forum Regular
Posts: 757
Joined: Wed Jan 13, 2010 7:22 pm

Re: php duplicate key message?

Post by mikosiko »

that is a function of the database (MySql in your case).... create a unique index on the column "roll"

here is how http://dev.mysql.com/doc/refman/5.0/en/ ... index.html
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Re: php duplicate key message?

Post by John Cartwright »

I personally wouldn't rely on mysql returning the error as an error check against duplicate entries, since schemas can be changed and key constraints are meant to deep the data integrity and triggering any internal errors is alarm enough for me that there is a better way to accomplish this. So, I usually perform a query to select the particular columns, and if exists, handle the error gracefully, i.e.,

Code: Select all

$sql = "
   SELECT COUNT(*)
   FROM users
   WHERE username = '". mysql_real_escape_string($username) ."'
   LIMIT 1
";
$result = mysql_query($sql) or die(mysql_error());
$return = mysql_fetch_assoc($result);

if ($return['count']) {
   // duplicate
} else { 
  // unique
}
Otherwise, if you truly want to rely on the key contrains, I tend to use the ON DUPLICATE KEY clause to perform an update on nothing, and check for the number of affected rows. I.e.,

Code: Select all

$sql = "
   INSERT INTO users
   SET username = '". mysql_real_escape_string($username) ."'
   ON DUPLICATE KEY UPDATE 1=1
";
$result = mysql_query($sql) or die(mysql_error());

if (mysql_affected_rows() == 0) {
   // duplicate
} else {
   // unique
}
Post Reply