How can prepared statements in PHP be utilized to prevent SQL injection when inserting multiple records into a database?

To prevent SQL injection when inserting multiple records into a database in PHP, prepared statements can be utilized. Prepared statements separate SQL code from user input, preventing malicious SQL code from being executed. By binding parameters to the prepared statement, the database engine can distinguish between SQL code and data, ensuring safe execution.

// Assume $conn is the database connection object

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

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

// Bind parameters and execute the statement for each record
foreach ($data as $record) {
    $stmt->bind_param("ss", $record[0], $record[1]);
    $stmt->execute();
}

// Close the statement and connection
$stmt->close();
$conn->close();