Before inserting into the database, I\'m using the following code to check for duplicates. To me, a duplicate is only considered a duplicate when name
, de
You can still run into race conditions where 2 users try to insert dups at the same time, checking for dups using a select statement simultaneously gives both users the go ahead to insert their records. I prefer to set unique index on the DB and then catch the error that bubbles up from the DB.
You want to do the following:
$dupesql = "SELECT * FROM table where (name = '$name' AND description = '$description' AND manufacturer = '$manufacturer' AND city ='$city' AND price = '$price' AND enddate = '$end_date')";
$duperaw = mysql_query($dupesql);
if (mysql_num_rows($duperaw) > 0) {
//your code ...
}
See Here for more information.
As I see it your question can be broken down into 2 parts. Why is my PHP code not working? I don't know, don't know much PHP and other people seem to have just answered that :-). The second question is how can I check for duplicates? You're checking for duplicates the completely wrong way.
Create a unique index / primary key on your table. Then when you try to insert the DB will throw an error if there's a duplicate. Catch the error and deal with it how you want. Counting the number of records is definitely the wrong way to go and will be a significant detriment to the speed of your code.
Try Following
INSERT IGNORE INTO person_tbl (last_name, first_name)
-> VALUES( 'Jay', 'Thomas');
Try this one:
foreach($states_to_add as $item) {
$dupesql = "SELECT
name
FROM
table
WHERE
(name = '$name'
AND description = '$description'
AND manufacturer = '$manufacturer'
AND city ='$city'
AND price = '$price'
AND enddate = '$end_date'
)";
$duperaw = mysql_query($dupesql);
if( mysql_num_rows($duperaw) ) {
echo nl2br("$name already exists in $city \n");
}
else {
$sql = "INSERT INTO table (..... (here go the values to be inserted)
You don't need to check for uniqueness in PHP, you can just do the whole test in MySQL:
INSERT INTO table1 (name, description, ......)
SELECT name1, description1, manufacturer1, city1, price1, enddate1
FROM (SELECT * FROM (
SELECT
@name:= '$name' as name1
,@description:= '$description' as description1
,.....
FROM DUAL as d1
LEFT JOIN table1 t1
ON (t1.name = d1.name1
AND t1.description = d1.description1
AND ......)
WHERE t1.name IS NULL) s1) s2
This will only insert the values if they pass the uniqueness test.