[英]Check that data in a SQL table already exists
I want to log what a user enters into a PHP form, and make sure they are not entering data that already exists in a database table. 我想记录用户输入PHP表单的内容,并确保他们没有输入数据库表中已经存在的数据。
I have the code already that enters the data into the table from user input, but I'm not sure how to check for duplicates. 我已经有了将用户输入的数据输入表中的代码,但是我不确定如何检查重复项。 For example I want to check that there is no product under the same name being added again.
例如,我要检查是否没有再次添加相同名称的产品。
This is what I have so far: 这是我到目前为止的内容:
$sql = "INSERT INTO user_data (product_name, code, comments)
VALUES ('$_POST[product_name]','$_POST[code]','$_POST[comments]')";
This is terrible SQL coding practice and, as stated before, is vulnerable to SQL Injection Attacks but something along these lines should work. 这是可怕的 SQL编码实践,并且如前所述,很容易受到SQL注入攻击的侵害,但应遵循这些原则。
$sql = "
INSERT INTO user_date
SELECT
product_name = '$_POST[product_name]'
,code = '$_POST[code]'
,comments = '$_POST[comments]'
WHERE
NOT EXISTS(SELECT * FROM user_data WHERE product_name = '$_POST[product_name]') ";
The best way to do this is by adding a uniqueness constraint to your table itself. 最好的方法是向表本身添加唯一性约束。 This way you can prevent duplicate records from being added.
这样,您可以防止添加重复的记录。
In your case I would go with this: 在您的情况下,我可以这样做:
ALTER TABLE `user_data` ADD UNIQUE (
`product_name`
)
Also, you could check for the record before you add it: 另外,您可以在添加记录之前检查记录:
$sql="SELECT count(*) AS number FROM user_data WHERE product_name LIKE '".$_POST['product_name']."'";
If the column "number" 1 (or bigger), you know it already exists. 如果列“数字”为1(或更大),则说明它已经存在。 Also when you get 2, or bigger, you will know that you already have duplicate records.
同样,当您得到2或更大时,您将知道您已经有重复的记录。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.