What is the correct syntax for adding multiple rows to a MySQL table using PHP?
When adding multiple rows to a MySQL table using PHP, you can use a single INSERT statement with multiple value sets separated by commas. This can be achieved by constructing a query string with the values for each row and executing it using the mysqli_query() function in PHP.
<?php
// Establish a connection to the MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Array of values for the multiple rows to be inserted
$values = [
['John', 'Doe', 'john@example.com'],
['Jane', 'Smith', 'jane@example.com'],
['Alice', 'Johnson', 'alice@example.com']
];
// Construct the INSERT query with multiple value sets
$query = "INSERT INTO users (first_name, last_name, email) VALUES ";
foreach ($values as $row) {
$query .= "('{$row[0]}', '{$row[1]}', '{$row[2]}'),";
}
$query = rtrim($query, ','); // Remove the last comma
// Execute the query to insert multiple rows
$result = mysqli_query($connection, $query);
// Check if the query was successful
if ($result) {
echo "Multiple rows inserted successfully.";
} else {
echo "Error: " . mysqli_error($connection);
}
// Close the database connection
mysqli_close($connection);
?>
Keywords
Related Questions
- What are some common methods for formatting PDFs with headers and text in PHP?
- What are the advantages of using an IDE like Aptana or Netbeans for PHP development, especially in the context of browser game projects?
- How can the PHP rename() function be used effectively in scenarios like copying files without extensions?