Asked 2 years ago
17 Jun 2021
Views 467
Alexis

Alexis posted

How insert multiple rows in mysql table with php array?

How insert multiple rows in mysql table with php array?
sachin

sachin
answered Apr 28 '23 00:00

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.
Post Answer