Tags
PHP , MySQL
Asked 3 years ago
17 Jun 2021
Views 626
Winifred

Winifred posted

how to insert multiple rows with different IDs in PHP MySQL

how to insert multiple rows with different IDs in PHP MySQL
python

python
answered Apr 28 '23 00:00

To insert multiple rows with different IDs in PHP MySQL, you can use a loop to insert each row individually. Here's an example:

Assuming you have an array of data that you want to insert, you can use a foreach loop to iterate over each item in the array and insert it into the database:



// Sample data to insert
$data = array(
    array('id' => 1, 'name' => 'John'),
    array('id' => 2, 'name' => 'Jane'),
    array('id' => 3, 'name' => 'Bob')
);

// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Loop through data and insert each row
foreach ($data as $row) {
    $id = $row['id'];
    $name = $row['name'];
    
    // Prepare insert statement
    $stmt = $mysqli->prepare("INSERT INTO my_table (id, name) VALUES (?, ?)");
    $stmt->bind_param("is", $id, $name);
    
    // Execute insert statement
    $stmt->execute();
    
    // Close statement
    $stmt->close();
}

// Close database connection
$mysqli->close();

In this example, we first define an array of data that we want to insert . We then connect to our MySQL database and use a foreach loop to iterate over each item in the array.

Inside the loop, we extract the ID and name from the current item and prepare an insert statement using the mysqli::prepare() method. We then bind the ID and name parameters to the statement using the mysqli_stmt::bind_param() method and execute the statement using the mysqli_stmt::execute() method.

Finally, we close the statement and loop to the next item in the array. Once all items have been inserted, we close the database connection.
Post Answer