Batch insert in php mysql

<?php
$sql = array();
foreach( $data as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['name']).'", '.$row['email'].')';
}
mysql_query('INSERT INTO test (name, email) VALUES '.implode(',', $sql));
?>

Using MySQLIi :

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}$sql = "INSERT INTO test (name, email)
VALUES ('Saurabh', 'saurabh@coding4developers.com');";
$sql .= "INSERT INTO test (name, email)
VALUES ('Gaurav', 'gaurav@coding4developers.com');";
$sql .= "INSERT INTO test (name, email)
VALUES ('Sachin', 'sachin@coding4developers.com');";if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}$conn->close();
?>

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *