2017-06-12 48 views
1

我从CSV文件中提取行,但在插入时,跳过了一些记录。有什么解决方案?php和pdo跳过一些记录插入

while(($line = fgetcsv($file, 10000, ",")) !== FALSE){ 

      $total_data++; 
      $sql="SELECT id FROM customers WHERE id ='".$line[0]."'"; 
      $db->query( $sql); 

      $check = $db->resultset(); 
      $num = $db->rowCount(); 

      if($num > 0){ 
       $update_data++; 
       //$db->query("UPDATE customers SET name = :name, phone=:phone where id=:id"); 
       $db->bind(':name', $line[1]); 
       $db->bind(':phone', $line[2]); 
       $db->bind(':id', $line[0]); 
       $db->execute(); 

      }else{ 
        $insert_data++; 
       $db->query("INSERT INTO customers(id,name,phone) VALUES (:id,:name,:phone)"); 
        $db->bind(':id',$line[0]); 
        $db->bind(':name', $line[1]); 
        $db->bind(':phone', $line[2]); 
        $db->execute(); 
      } 
     } 

回答

0

通常与PDO你必须存储调用query()等的结果,并呼吁返回预处理语句的方法...

query()返回PDOStatement对象,以便保存在一个变量,例如$statement,然后调用该变量像rowCount()方法:

while(($line = fgetcsv($file, 10000, ",")) !== FALSE){ 
    $total_data++; 
    $sql="SELECT id FROM customers WHERE id ='".$line[0]."'"; 
    $statement = db->query( $sql); 

    $check = $statement->resultset(); 
    $num = $statement->rowCount(); 

    if($num > 0){ 
     $update_data++; 
     $updateStatement = $db->query("UPDATE customers SET name = :name, phone=:phone where id=:id"); 
     $updateStatement->bind(':name', $line[1]); 
     $updateStatement->bind(':phone', $line[2]); 
     $updateStatement->bind(':id', $line[0]); 
     $updateStatement->execute(); 

    }else{ 
     $insert_data++; 
     $insertStatement = db->query("INSERT INTO customers(id,name,phone) VALUES (:id,:name,:phone)"); 
     $insertStatement->bind(':id',$line[0]); 
     $insertStatement->bind(':name', $line[1]); 
     $insertStatement->bind(':phone', $line[2]); 
     $insertStatement->execute(); 
    } 
} 
+0

可以使用条件来检查记录插入或没有,如果是,那么什么样的方式。 – yogendra

+0

是的[rowcount()](http://php.net/manual/en/pdostatement.rowcount.php) - 阅读描述和示例 - 虽然该示例可能是一个DELETE查询,它将应用于一个INSERT查询以及 –

+0

@yogendra per [rowCount()](http://php.net/manual/en/pdostatement.rowcount.php):“_ ** PDOStatement :: rowCount()**返回受影响的行数通过相应的PDOStatement对象执行的最后一个DELETE,INSERT或UPDATE语句。“所以,如果您在运行'$ insertStatement-> execute();之后查看我的答案中的代码,”调用'$ insertStatement-> rowCount();'应该产生受_INSERT_查询影响的行数 –