简体   繁体   中英

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.

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 = "
    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. Also when you get 2, or bigger, you will know that you already have duplicate records.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM