如果数据存在,则阻止将数据插入数据库

How to prevent inserting data to database if data is exist in database

ex : I have data

for ($i = 1; $i <= 10; $i++) {
    $text = "Orange";
    mysql_query("INSERT INTO fruit (text) VALUES ('$text')");
}

I want the text "orange" is inserted once to the "fruit" table
and if there is text "Orange" again its not inserted to the "fruit" table
because the data is exist and have been inserted before

for ($i = 1; $i <= 10; $i++) {
$text = "Orange";
$result = mysql_query("SELECT text FROM fruit WHERE text = '$text');
    if (mysql_num_rows($result) == 0){
        mysql_query("INSERT INTO fruit (text) VALUES ('$text')");
    }else{
       echo "Duplicate";
       break;
     }
}

Make the column as Unique key...
This will prevent the duplicates

References:
Primary Key and Unique Key constraints

Use INSERT IGNORE with unique key on text.

INSERT IGNORE INTO fruit (text) VALUES ('$text')

Couple ways:

  • You would have to perform a select First and compare the results and then do the insert if no records found
  • Add Unique to your datbase fields and insers won't be performed if there is a data
  • Construct your query to check before insert
  • Use Insert Ignore

Another way is to use:

REPLACE INTO fruit (text) VALUES ('$text')

will insert new ones and for old ones, delete and insert again :)
But adding unique index on text field is the best way :D

Most things in SQL are just like MySQL Unique Indexes, we learn just once.
Solving your example, we shall run something near

CREATE  TABLE IF NOT EXISTS `stackoverflow2`.`fruit` (
  `id` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
  `text` VARCHAR(50) NOT NULL ,
  PRIMARY KEY (`id`) ,
  UNIQUE INDEX `text_UNIQUE` (`text` ASC) )
ENGINE = InnoDB;

From MySQL doc,

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. [...]