To insert multiple rows into a MySQL table with a PHP array, you can use a loop to iterate through the array and execute an insert query for each row. Here's an example:
Assuming you have a MySQL table named "users" with columns "name" and "email", and an array of user data like this:
$userData = array(
array('John', 'john@example.com'),
array('Jane', 'jane@example.com'),
array('Bob', 'bob@example.com')
);
You can use a loop to insert each row into the "users" table:
// Connect to MySQL
$conn = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
// Loop through the user data array
foreach ($userData as $user) {
$name = $user[0];
$email = $user[1];
// Execute the insert query
$query = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
mysqli_query($conn, $query);
}
// Close the connection
mysqli_close($conn);
In the loop, we extract the name and email values from each row in the array and execute an insert query using mysqli_query () function. Finally, we close the database connection.
Note: It's important to sanitize and validate user input before inserting it into the database to prevent SQL injection attacks. You can use prepared statements or parameterized queries to achieve this.