Skip to content
PHP Logo

How can prepared statements in PDO be optimized for inserting arrays into a database in PHP?

To optimize prepared statements in PDO for inserting arrays into a database in PHP, you can use a loop to bind each array element as a parameter in the prepared statement. This way, you can insert multiple rows efficiently without the need to prepare the statement for each array element.

php
// Assume $pdo is your PDO connection and $dataArray is the array to be inserted

// Prepare the statement with placeholders
$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");

// Bind parameters for each array element and execute the statement in a loop
foreach ($dataArray as $data) {
    $stmt->bindParam(':value1', $data['value1']);
    $stmt->bindParam(':value2', $data['value2']);
    $stmt->execute();
}