开发者

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

开发者_Go百科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')");


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

ALTER TABLE questions ADD UNIQUE(question_text);


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜