How can PHP arrays be utilized to insert multiple values into a database table?
To insert multiple values into a database table using PHP arrays, you can utilize a foreach loop to iterate through the array of values and execute an INSERT query for each value. This allows you to efficiently insert multiple rows into the database table in a single script execution.
// Sample array of values to insert into the database
$data = [
['John', 'Doe'],
['Jane', 'Smith'],
['Alice', 'Johnson']
];
// Connect to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');
// Iterate through the array and insert values into the database
foreach($data as $row) {
$query = "INSERT INTO users (first_name, last_name) VALUES ('" . $connection->real_escape_string($row[0]) . "', '" . $connection->real_escape_string($row[1]) . "')";
$connection->query($query);
}
// Close the database connection
$connection->close();