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.
Link to comment
Share on other sites

[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
Link to comment
Share on other sites

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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.