Insert Multiple record in DB

PHP MySQL Insert Multiple Records

  • In php insert multiple record in data table. with use the mysqli_multi_query() function is used.
MySQLi Object-Oriented

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "student";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO student_data (first_name, second_name, email, DOB) VALUES ('ram', 'sharma', 'ram@gmail.com', '1999-07-02')";
$sql = "INSERT INTO student_data (first_name, second_name, email, DOB) VALUES ('sita', 'sharma', 'ram@gmail.com', '1999-07-02')";
$sql = "INSERT INTO student_data (first_name, second_name, email, DOB) VALUES ('laxman', 'sharma', 'ram@gmail.com', '1999-07-02')";

if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();
?>

MySQLi Procedural

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "student";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection

if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

$sql = "INSERT INTO student_data (first_name, second_name, email, DOB) VALUES ('ram', 'sharma', 'ram@gmail.com', '1999-07-02')";
$sql = "INSERT INTO student_data (first_name, second_name, email, DOB) VALUES ('sita', 'sharma', 'ram@gmail.com', '1999-07-02')";
$sql = "INSERT INTO student_data (first_name, second_name, email, DOB) VALUES ('laxman', 'sharma', 'ram@gmail.com', '1999-07-02')";

if (mysqli_multi_query($conn, $sql)) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "
" . mysqli_error($conn);
}

mysqli_close($conn);
?>

PDO

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "student";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// begin the transaction
$conn->beginTransaction();
// our SQL statements

$sql = "INSERT INTO student_data (first_name, second_name, email, DOB) VALUES ('ram', 'sharma', 'ram@gmail.com', '1999-07-02')";
$sql = "INSERT INTO student_data (first_name, second_name, email, DOB) VALUES ('sita', 'sharma', 'ram@gmail.com', '1999-07-02')";
$sql = "INSERT INTO student_data (first_name, second_name, email, DOB) VALUES ('laxman', 'sharma', 'ram@gmail.com', '1999-07-02')";

// commit the transaction
$conn->commit();
echo "New records created successfully";
} catch(PDOException $e) {
// roll back the transaction if something failed
$conn->rollback();
echo "Error: " . $e->getMessage();
}

$conn = null;
?>