What is the recommended approach for inserting multiple data from an array into a database using PDO in PHP?
When inserting multiple data from an array into a database using PDO in PHP, it is recommended to use prepared statements within a loop to efficiently insert each set of data. This approach helps prevent SQL injection attacks and improves performance by reducing the number of database queries.
// Assuming $dataArray is an array of arrays containing the data to be inserted
// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare the SQL statement
$stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (:value1, :value2)");
// Loop through the array and insert each set of data
foreach($dataArray as $data) {
$stmt->execute(array(':value1' => $data['value1'], ':value2' => $data['value2']));
}