Jump to content

how do I code to check for a duplicate key on mysql insert?


cgchris99

Recommended Posts

Before inserting the information use a select query, call the values you want to check and then compare them with the variables you already have defined.  Then use an IF statement to check whether or not it's the same or not. If not then insert the information, if so return an error to the user.
[quote author=Fearsoldier link=topic=121531.msg499847#msg499847 date=1168272457]
Before inserting the information use a select query, call the values you want to check and then compare them with the variables you already have defined.
[/quote]

A query is a good idea, but a comparison isn't.  A row count would be easier in this situation...

Example: A user enters their email address (unique column in the database)...

[code]<?php
$sql = "SELECT * FROM member_details WHERE email = '$user_entered_email_address'";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0){
  // Sorry, the row exists, maybe display the form again
}
else {
  // The row doesn't exist, maybe put your insert code in here
}
?>[/code]

Regards
Huggie
if you are using keys then this process should never bee required - keys are there to help you link things together - every record in a table (where that record is a foreign key in another table) should have a uniquie key and as such you should use primary key with auto_increment.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.