How insert to mysql many rows using php?

by tressie.damore , in category: PHP General , 2 months ago

How insert to mysql many rows using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 2 months ago

@tressie.damore 

To insert multiple rows into a MySQL database using PHP, you can use the "INSERT INTO" statement with a loop to dynamically insert the rows. Here is an example of how you can achieve this:

 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
28
29
30
// Connection to MySQL database
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "your_database";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Array of rows to be inserted
$rows = array(
    array('John', 'Doe', 25),
    array('Jane', 'Smith', 30),
    // Add more rows as needed
);

// Prepare and execute the SQL insert statement
$sql = 'INSERT INTO your_table_name (first_name, last_name, age) VALUES (?, ?, ?)';
$stmt = $conn->prepare($sql);

foreach ($rows as $row) {
    $stmt->bind_param('ssi', $row[0], $row[1], $row[2]);
    $stmt->execute();
}

// Close the prepared statement and database connection
$stmt->close();
$conn->close();


In this example, you would need to replace "your_username", "your_password", "your_database", "your_table_name" with your own values. Also, make sure that the number of placeholders ("?") in the SQL statement matches the number of columns in your table.