How can the code provided be optimized to handle a dynamic number of data entries for insertion into a database in PHP?

To optimize the code for handling a dynamic number of data entries for insertion into a database in PHP, we can use prepared statements with parameter binding to efficiently insert multiple records with varying values. This approach helps prevent SQL injection attacks and improves performance by reducing the number of queries sent to the database.

// Assuming $data is an array of arrays containing the data to be inserted

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=your_database", "username", "password");

// Prepare the INSERT statement
$stmt = $pdo->prepare("INSERT INTO your_table (column1, column2) VALUES (:value1, :value2)");

// Iterate through each data entry and execute the prepared statement
foreach ($data as $entry) {
    $stmt->execute([
        'value1' => $entry['value1'],
        'value2' => $entry['value2']
    ]);
}