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
php duplicate key message?
Moderator: General Moderators
-
adilmarwat2004
- Forum Commoner
- Posts: 44
- Joined: Fri Sep 04, 2009 11:28 pm
Re: php duplicate key message?
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
here is how http://dev.mysql.com/doc/refman/5.0/en/ ... index.html
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
Re: php duplicate key message?
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.,
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 = "
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
}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
}