How to insert into database with multiple array in php?

Member

by kadin , in category: PHP General , 2 months ago

How to insert into database with multiple array in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by daisha , 2 months ago

@kadin 

To insert data into a database with multiple arrays in PHP, you can follow these steps:

  1. Establish a database connection using PDO or MySQLi.
  2. Prepare your SQL INSERT statement with placeholders for the values you want to insert.
  3. Loop through your arrays and execute the INSERT statement for each set of values.
  4. Bind the values from the arrays to the placeholders in the INSERT statement.
  5. Execute the prepared statement.


Here's an example using PDO:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
// Assuming you have already established a database connection using PDO

// Arrays containing the data to insert
$array1 = array("John", "Doe", "25");
$array2 = array("Jane", "Smith", "30");

// SQL INSERT statement
$sql = "INSERT INTO your_table (first_name, last_name, age) VALUES (?, ?, ?)";

// Prepare the statement
$stmt = $pdo->prepare($sql);

// Loop through the arrays and execute the INSERT statement
foreach ([$array1, $array2] as $array) {
    // Bind the values from the array to the placeholders
    $stmt->bindValue(1, $array[0]);
    $stmt->bindValue(2, $array[1]);
    $stmt->bindValue(3, $array[2]);
    
    // Execute the statement
    $stmt->execute();
}

// Close the database connection
$pdo = null;
?>


Note: This example assumes you have already established a database connection using PDO. You'll need to modify the code accordingly if you're using MySQLi or a different database connection method.