Ebadly.Decipher
Ebadly.Decipher

Reputation: 81

How to avoid duplication of mysql table entries?

I seem to be getting duplicating table entries with using this PHP code. Every time I hit refresh, when it inserts what I have hard coded and prints previous entries (even if they values are the same).

What I want to know is how can I avoid duplication if the values are the same? I also do not want the code to duplicate entries when the page refreshes.

//insert data entries
mysqli_query ($con, "INSERT IGNORE INTO alarms(Title, Description, DT)
    VALUES('get', 'Agha will eat', '2013-08-05 00:15:12')");

This is the print function.

//print out data entries
$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'];
 }

Upvotes: 1

Views: 384

Answers (1)

MD Sayem Ahmed
MD Sayem Ahmed

Reputation: 29166

Create a UNIQUE constraint in your alarm table based on the values which you want to be unique.

Suppose that for every row, you want the Title, Description and DT triples to be unique. Then, add the UNIQUE constraint in your alarm table in the following way -

ALTER TABLE alarm ADD CONSTRAINT uc_alarm UNIQUE (Title, Description, DT)

If you do this, then whenever you try to insert a row whose Title, Description and DT matches with those of an existing rows, MySQL will generate an error and reject that insert command.

Check out this short tutorial for a overview of the UNIQUE constraint.

Upvotes: 2

Related Questions