Page 1 of 1

php duplicate key message?

Posted: Fri May 07, 2010 4:49 am
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

Re: php duplicate key message?

Posted: Fri May 07, 2010 7:37 am
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

Re: php duplicate key message?

Posted: Fri May 07, 2010 4:22 pm
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
}