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:
$data = array(155, 165, 175, 185);
Traditionally, one would create a loop to execute multiple INSERT statements, such as:
for($j = 0; $j prepare("INSERT INTO table SET memberID=?, programID=?, date_added=NOW()");
$stmt->execute(array($memberid, $data[$j]));
}
However, building a single dynamic SQL statement is considered more efficient. A possible solution would be:
$sql = array();
foreach( $data as $row ) {
$sql[] = '("'.$memberid.'", "'.$row[$j].'", NOW()")';
}
mysql_real_query('INSERT INTO table (memberid, programid) VALUES '.implode(',', $sql));
With PDO, a more suitable approach is:
$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);
}
This technique allows inserting multiple rows into a database table using a single prepared statement, reducing the number of database calls and improving performance.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3