简体   繁体   中英

Why is this PDO Insert executing twice?

This has been inserting each line from the csv into the database twice, and now today three times. Nothing else I put in the loop happens more than it should.

$file_handle = fopen("uploads/numbers.csv", "r");    
$stmt = $db->prepare("INSERT INTO database
(firstname,lastname,phonenumber) VALUES
(:field1,:field2,:field3)");

while (($line_of_data = fgetcsv($file_handle, 1000, ",")) !== FALSE) 
{
$stmt->execute(array(':field1' => $line_of_data [0], ':field2' => $line_of_data[1], ':field3' => $line_of_data[2]));
}

Setup a proper primary key on database. Either (firstname, lastname) or (firstname, lastname, phonenumber) depending on the usage. Ta-da, no more duplicates.

I'm going to assume James was right in the columns by the fact that the CSV contains preexisting data in the database, but either way, a primary key will prevent duplicates.

If you use the firstname, lastname key and you want to have the script be able to update the phone number, you could use REPLACE instead of INSERT.

Your check is here:

while (($line_of_data = fgetcsv($file_handle, 1000, ",")) !== FALSE) 

First, you don't need the !== FALSE . It can just be this:

while (($line_of_data = fgetcsv($file_handle, 1000, ","))) 

Also, your code is just checking while that fgetcsv is not empty. So what if there is an empty line in the file? It gets run twice. So how about this:

while (($line_of_data = trim(fgetcsv($file_handle, 1000, ",")))) {
  if (!empty($line_of_data)) {
    $stmt->execute(array(':field1' => $line_of_data [0], ':field2' => $line_of_data[1], ':field3' => $line_of_data[2]));
  }
}

The idea is that when you call fgetcsv let's trim the line to get rid of extra stuff like maybe a line break at the end of the line. Then the if (!empty($line_of_data)) { checks if the line is not empty & only acts on the query if it is definitely not empty. If somehow trim(fgetcsv(…)) doesn't work, you can do it this way instead:

while (($line_of_data = fgetcsv($file_handle, 1000, ","))) {
  if (!empty(trim($line_of_data))) {
    $stmt->execute(array(':field1' => $line_of_data [0], ':field2' => $line_of_data[1], ':field3' => $line_of_data[2]));
  }
}

With all of that logic in if (!empty(trim($line_of_data))) { .

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