Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP-从mysql中具有一致列的多个CSV文件中插入多行_Php_Mysql_Csv - Fatal编程技术网

PHP-从mysql中具有一致列的多个CSV文件中插入多行

PHP-从mysql中具有一致列的多个CSV文件中插入多行,php,mysql,csv,Php,Mysql,Csv,多个CSV文件具有一致的26列标题。我使用普通PHP在MySQL中插入数据。数据可能包含>100k行 这是我的示例CSV文件 以下是我的代码: while(($line = fgetcsv($csvFile)) !== FALSE){ //to get the data from csv $account_code = $line[0]; $caller_number = $line[1]; $callee_number = $line[2]; . .

多个CSV文件具有一致的26列标题。我使用普通PHP在MySQL中插入数据。数据可能包含>100k行

这是我的示例CSV文件

以下是我的代码:

while(($line = fgetcsv($csvFile)) !== FALSE){
    //to get the data from csv
    $account_code = $line[0];
    $caller_number = $line[1];
    $callee_number = $line[2];
  .
  .
  .

    $action_type=$line[23];
    $source_trunk_name=$line[24];
    $dest_trunk_name =$line[25];

    $query = $db->query("INSERT INTO `cdrnew`
                (`account_code`, `caller_number`, `callee_number`, ...........,`action_type`, `source_trunk_name`, `dest_trunk_name`)
            VALUES ('".$account_code."','".$caller_number."', '".$callee_number."', ............,'".$action_type."','".$source_trunk_name."','".$dest_trunk_name."')");

如果我在所有CSV文件中都有一致的26列标题,那么这是将数据从CSV插入MySQL的正确方法吗。或者有更好的方法吗?

我建议使用参数化和绑定查询。除了显而易见的好处之外,消除查询的可能性的好处是,您可以编译查询一次,但每次都使用新参数多次运行查询。 这使数据库不再需要进行1000次查询编译,从而避免了1000次不必要的往返服务器的过程

首先将查询移到循环之外,并在那里进行准备

$stmt = $db->prepare("INSERT INTO `cdrnew`
                (`account_code`, `caller_number`, `callee_number`, 
                .,.,.,.,.,.,
                `action_type`, `source_trunk_name`, `dest_trunk_name`)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";

while(($line = fgetcsv($csvFile)) !== FALSE){

    $stmt->bind_param('ssssssssssssssssssssssssss',
                        $line[0], $line[1], $line[2], $line[3], $line[4],
                        $line[5], $line[6], $line[7], $line[8], $line[9],
                        $line[10], $line[11], $line[12], $line[13], $line[14],
                        $line[15], $line[16], $line[17], $line[18], $line[19],
                        $line[20], $line[21], $line[22], $line[23], $line[24],
                        $line[25]
        );
    $stmt->execute();
}
注意:您可能希望在此基本布局中添加一些错误检查


不,而且由于许多原因,其中最重要的一个原因是您的脚本是开放的。甚至你也应该考虑使用<代码> MySqLII< <代码>或<代码> PDO//COD> API,而不是使用参数化的连接值。准备好的然后绑定的查询将允许您只编译一次查询,但执行它需要10万次。您的代码是否存在特定问题?否。使用此代码将数据插入mysql。但我怀疑我是否应该遵循这种方法。或者我们可以使用大容量插入或其他方法来提高性能?您使用的是哪种数据库扩展,
MySQLI
PDO