简体   繁体   中英

How to check if sql values already exist in a table to prevent duplicates?

I already created the sql database and table correctly,

but, when I try to print the values out in php by using a while loop, I noticed that I was getting duplicate values printed. At first I thought it was the while loop. Then I noticed that every time I ran the php code, I was getting more duplicates printed every time I ran the code. I don't want duplicates.

Here's how I wrote the code for the table:

$sql = "CREATE TABLE IF NOT EXISTS alarms (
    alarmID INT NOT NULL AUTO_INCREMENT,
    PRIMARY KEY (alarmID),
    Title CHAR(30),
    Description TEXT,
    DT DATETIME
    )";

Here is how I am inserting the values:

mysqli_query ($con, "INSERT INTO alarms(Title, Description, DT)
VALUES('eat', 'Agha loves eating', '2013-08-05 00:15:12')");

Here is my while loop that prints out the values:

$result = mysqli_query($con,"SELECT * FROM alarms");
while ($row = mysqli_fetch_array($result)){
echo $row['alarmID'] . " <br> " . $row['Title'] . " <br> " . $row['Description'] . " <br> " . $row['DT'];
}

How can I insert values while preventing duplicates?

I assume the code that inserts values is together with the code that prints them? Which means your insertion code is running each time you refresh, inserting the values again. You shouldn't be running the insertion code except when necessary.

However, to prevent duplicates when inserting data, you either need to do a check before inserting a value again, or you need to modify your query to prevent duplicates. Read these, they will help.

http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html <- How to write a query that will insert new records and fall back on an update if the record already exists.

http://dev.mysql.com/doc/refman/5.0/en/replace.html <- Similar result, different method.

These methods require that you have your primary key set to be unique, and that the components of the primary key are part of your insert query. If that is not possible, and your primary key is separate (such as an auto-increment), then your only choice is to check for the entry before creating it again.

if you want to just ignore dups then set unique key constrains and primary key then use INSERT IGNORE like

mysqli_query ($con, "INSERT IGNORE INTO alarms(Title, Description, DT)
    VALUES('eat', 'Agha loves eating', '2013-08-05 00:15:12')");

I think Your problem is - for a single mysql_inser() two record is inserting in Your DB. This problem happens when page is not properly reloaded . So After inserting on Alarm details , redirect Your page properly so that there will be no posted data and no insert request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM