在PHP脚本中将值插入MySQL DB之前检查值是否存在

问题描述:

我一直在寻找类似的问题,但没有成功.

I've looked for similar questions with no success.

我有这段代码:

form1.php

$query  = "INSERT INTO table1 ";
$query .= "(fname, lname, mail)";
$query .= " VALUES ";
$query .= "('".$_POST[fname]."', '".$_POST[lname]."', '".$_POST[mail]."')"; 

$result = mysql_query($query) or die ("Query Failed: " . mysql_error());

我希望脚本将检查插入的值是否存在于相应的列中,如果存在则抛出错误.有什么想法吗?

And I want that the script will check if the value inserted exists in the corresponding column, and throw an error if it does. any ideas?

在您关心的字段上创建UNIQUE密钥,并在事后检测完整性错误.

Create a UNIQUE key on the fields you care about, and detect the integrity error after the fact.