Home > Database > Mysql Tutorial > How Can I Efficiently Insert an Array of Values into a MySQL Database Using PDO?

How Can I Efficiently Insert an Array of Values into a MySQL Database Using PDO?

Barbara Streisand
Release: 2024-10-29 20:35:29
Original
270 people have browsed it

How Can I Efficiently Insert an Array of Values into a MySQL Database Using PDO?

Using PDO to Insert an Array into a MySQL Database with a Single Prepared Statement

When performing online enrollments, it's common to encounter situations where customers select multiple programs for enrollment. These programs can be represented as an array of three-digit integers. To insert these arrays into a database, a single prepared statement can be more efficient than multiple executions.

Example Scenario

Consider an array containing the following program IDs:

$data = [155, 165, 175, 185];
Copy after login

Traditional Loop Approach

A typical approach would involve iterating through the array and executing multiple INSERT statements:

<code class="php">for ($j = 0; $j < count($data) - 1; $j++) {
    $stmt = $db->prepare("INSERT INTO table SET memberID=?, programID=?, date_added=NOW()");
    $stmt->execute(array($memberid, $data[$j]));
}</code>
Copy after login

However, this method is less efficient than a single INSERT statement.

Dynamic SQL Statement

Building a single dynamic SQL statement is a more efficient option:

<code class="php">$sql = 'INSERT INTO table (memberID, programID) VALUES ';
$insertQuery = array();
$insertData = array();
foreach ($data as $row) {
    $insertQuery[] = '(?, ?)';
    $insertData[] = $memberid;
    $insertData[] = $row;
}
if (!empty($insertQuery)) {
    $sql .= implode(', ', $insertQuery);
    $stmt = $db->prepare($sql);
    $stmt->execute($insertData);
}</code>
Copy after login

This approach uses PDO to create a single prepared statement by concatenating placeholders with the appropriate data. It's important to validate the $insertQuery array before executing the statement to avoid empty insertions.

The above is the detailed content of How Can I Efficiently Insert an Array of Values into a MySQL Database Using PDO?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template