PHP PDO Mysql Insert Performance

前端 未结 3 1367
鱼传尺愫
鱼传尺愫 2021-01-28 03:43

I normally don\'t use a lot of SQL stuff in PHP but recently have been forced into it by a friend as to help him debug something.

I am using PDO with PHP to insert some

3条回答
  •  春和景丽
    2021-01-28 04:33

    As Simon stated in a comment, there is no use of doing the preparation within the loop. Doing so will cause 300 queries to be sent to the database, each time one for the preparation and on for the actual insert. Using the prepare-statement before will cause only 151 queries:

    $query = $data->prepare("INSERT INTO `tbl_temp` (aid, bid) VALUES (?, ?)");
    for ($i = 1; $i <= 150; $i++) {
        $time = time();
        $query->execute(array($i, $time));
    }
    

    Another idea could be to use instead a combined multi insert statement. I guess it could have a better performance, but I'm not quite sure:

    $query = 'INSERT INTO `tbl_temp` (aid, bid) VALUES';
    for ($i = 1; $i <= 150; $i++) {
        if ($i == 1) {
            $query .= ' ('.$i.', '.time().')';
        } else {
            $query .= ', ('.$i.', '.time().')';
        }
    }
    $data->exec($query);
    

提交回复
热议问题