php PDO insert batch multiple rows with placeholders

前端 未结 5 1444
失恋的感觉
失恋的感觉 2020-12-01 10:53

I am looking to do multiple inserts using PHP PDO.

The closest answer I have found is this one

how-to-insert-an-array-into-a-single-mysql-prepared-st

5条回答
  •  误落风尘
    2020-12-01 11:27

    I'm assuming you are using InnoDB so this answer is only valid for that engine (or any other transaction-capable engine, meaning MyISAM isn't included).

    By default InnoDB runs in auto-commit mode. That means each query is treated as its own contained transaction.

    To translate that to something us mortals can understand, it means that every INSERT query you issue will force hard-disk to commit it by confirming it wrote down the query information. Considering how mechanical hard-disks are super slow since their input-output operation per second is low (if I'm not mistaken, the average is 300ish IO's), it means your 50 000 queries will be - well, super slow.

    So what do you do? You commit all of your 50k queries in a single transaction. It might not be the best solution for various purposes but it'll be fast.

    You do it like this:

    $dbh->beginTransaction();
    
    $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
    
    foreach($valuesToInsert as $insertRow)
    {    
        // now loop through each inner array to match bound values
        foreach($insertRow as $column => value)
        {
            $stmt->bindParam(":$column", value);
            $stmt->execute();
        }
    }
    
    
    $dbh->commit();
    

提交回复
热议问题