简体   繁体   English

为什么此PDO插入执行两次?

[英]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. 这是将来自csv的每一行插入数据库两次,现在已经插入了三遍。 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. Ta-da,不再重复。

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. 我将假设James在列中是正确的,因为CSV包含数据库中预先存在的数据,但是无论哪种方式,主键都可以防止重复。

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. 如果您使用名字,姓氏键,并且希望脚本能够更新电话号码,则可以使用REPLACE代替INSERT。

Your check is here: 您的支票在这里:

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

First, you don't need the !== FALSE . 首先,您不需要!== 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. 此外,你的代码只是检查whilefgetcsv不是空的。 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. 这个想法是,当您调用fgetcsv让我们修剪一下行以消除多余的内容,例如行尾的换行符。 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 (!empty($line_of_data)) {检查行是否不为空,并且如果行绝对不为空,则仅对查询起作用。 If somehow trim(fgetcsv(…)) doesn't work, you can do it this way instead: 如果某种方式trim(fgetcsv(…))无法正常工作,则可以这样操作:

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))) { . if (!empty(trim($line_of_data))) {所有逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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