Abby
Abby

Reputation: 61

Don't insert entry if already exist

How to not insert the values if same question_text exist but not for the first_word.

Example (The question_text is the whole sentence and the first word is the first word in the sentence.)

He is crazy. //insert

He is smart. //insert

He is smart. //exist don't insert

$first_word = current(explode(' ', $_POST['question_text']));

mysql_query("INSERT INTO questions (question_id,question_text,field_name)
             VALUES ('','$_POST[question_text]','$first_word')");

Upvotes: 1

Views: 598

Answers (3)

JRL
JRL

Reputation: 78033

MySQL has the INSERT ON DUPLICATE KEY UPDATE statement, which you could use. But in the example you posted it would probably not be a good way to do it.

Upvotes: 0

powtac
powtac

Reputation: 41080

You could run this SQL once query to prevent double entries with the same content:

ALTER TABLE questions ADD UNIQUE(question_text);

Upvotes: 3

Jon
Jon

Reputation: 437734

You can't do that with this query. You need to write another query first to check for the existence of the row you don't want to duplicate.

Also, the code is vulnerable to SQL injection attacks. See here for information on how to fix that: Protect against SQL injection

Upvotes: 0

Related Questions