How can SQL queries be optimized for inserting data into multiple rows in a table in PHP?

When inserting data into multiple rows in a table in PHP, one way to optimize SQL queries is to use prepared statements with parameter binding. This can help improve performance by reducing the number of query executions and minimizing the risk of SQL injection attacks. By preparing the SQL statement once and then executing it multiple times with different parameter values, you can efficiently insert multiple rows of data into the table.

// Sample code to insert multiple rows into a table using prepared statements

// Sample data to be inserted
$data = [
    ['John', 'Doe'],
    ['Jane', 'Smith'],
    ['Alice', 'Johnson']
];

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');

// Prepare the SQL statement with placeholders
$stmt = $pdo->prepare("INSERT INTO users (first_name, last_name) VALUES (?, ?)");

// Iterate over the data and execute the prepared statement with each row
foreach ($data as $row) {
    $stmt->execute($row);
}

// Close the database connection
$pdo = null;