Home > Database > Mysql Tutorial > How to Efficiently Insert Multiple Rows into a MySQL Table Using PHP and PDO?

How to Efficiently Insert Multiple Rows into a MySQL Table Using PHP and PDO?

Barbara Streisand
Release: 2024-10-29 11:52:29
Original
217 people have browsed it

How to Efficiently Insert Multiple Rows into a MySQL Table Using PHP and PDO?

Inserting Arrays into MySQL with PHP and PDO

When initializing online programs, customers may enroll in multiple programs represented as three-digit integers and stored in an array. For example, to enroll in programs 155, 165, 175, and 185, the following array would be used:

<code class="php">$data = array(155, 165, 175, 185);</code>
Copy after login

Traditionally, one would create a loop to execute multiple INSERT statements, such as:

<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, building a single dynamic SQL statement is considered more efficient. A possible solution would be:

<code class="php">$sql = array();
foreach( $data as $row ) {
    $sql[] = '("'.$memberid.'", "'.$row[$j].'", NOW()")';
}
mysql_real_query('INSERT INTO table (memberid, programid) VALUES '.implode(',', $sql));</code>
Copy after login

With PDO, a more suitable approach is:

<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 technique allows inserting multiple rows into a database table using a single prepared statement, reducing the number of database calls and improving performance.

The above is the detailed content of How to Efficiently Insert Multiple Rows into a MySQL Table Using PHP and 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