我有以下代码,我想更有效地执行对数据库的插入操作,并更新代码以现在使用PDO:

foreach ($urls as $i => $url) {


    //path to csv file
    $web = "http://path-to-file/".$url;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt");
    curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
    curl_setopt ($ch, CURLOPT_URL, $web);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch, CURLOPT_TIMEOUT, 30);
    $result = curl_exec($ch);

    //explode the csv file by new line
    $r = explode("\n", $result);

    $sql = "insert into product (`product_name`) values ";

    for ($i = 1; $i <= count($r); $i++){

        //explode each row by comma
        $n = explode(",", $r[$i]);
        $product_name = $n[0];


        $sql .= "('$product_name'),";


    }

    $sql = trim($sql, ",");

    if(count($n) != 0)
        mysql_query($sql);

}


首先,存在一个循环,该循环从远程文件中检索数据并将所有这些数据从文件插入数据库。此刻,代码从一个文件插入数据,然后移至下一个文件。每个文件最多可以有2000个插入,通常每15个批次进行一次(因此插入的记录总数约为30000)。在数据库中一次命中或批量插入所有30000条记录会更有效吗? (请注意,该站点上可能有多个用户也在检索文件并执行插入操作)。

其次,我想修改上面的代码以使用PDO。

任何帮助,将不胜感激。

谢谢

PS。我确实知道如何创建PDO数据库连接。

最佳答案

要用最简单的代码做到这一点:

// Start PDO connection (DataBaseHandler)
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO('mysql:host=localhost;dbname=database', $user, $password);

// Prepare a reusable insert statement and bind the variable
$insert = $dbh->prepare("INSERT INTO product (`product_name`) VALUES (:product_name)");
$insert->bindParam(':product_name',$product_name);

// Use foreach for arrays
foreach($r as $row){
    //explode each row by comma
    $n = explode(",", $row);
    $product_name = $n[0];

    // Execute the prepared INSERT statement referring to the current product name
    $insert->execute();
}


不知道在一个语句中执行### INSERTS是否比在单独的###中执行INSERT语句要快,但是由于PDO准备好的语句,该代码肯定更简单,有效:
http://www.php.net/manual/en/pdo.prepare.php

编辑:

根据this answer,执行一个大查询要快得多。希望我能帮助您开始使用PDO和准备好的语句,但是您可以从中学到最好的知识,以便创建新的PDO查询。这可能会让您入门:https://stackoverflow.com/a/6235710/703229

07-27 19:31