Thêm (insert) nhiều record dữ liệu trong MySQL với PHP

Đây là bài 49/53 bài của series môn học Lập trình Web PHP

Trong bài này, chúng ta sẽ tìm hiểu về cách insert multiple records vào table trong MySQL với PHP. Để học tốt bài này, các bạn cần đọc lại bài Cài đặt môi trường lập trình Web PHP với XAMPP để biết cách chạy ứng dụng web PHP với XAMPP.

Các ví dụ insert dữ liệu sẽ thực hiện trên table gochocit_posts trong database gochocit. Database và table này đã được tạo trong bài Tạo database và tạo table trong MySQL với PHP. Các bạn cần đọc lại để xem cấu trúc của database và table trên.

Bảng gochocit_posts được tạo ra

1. Thêm (insert) multiple records sử dụng MySQLi (object-oriented)

Nhiều câu lệnh INSERT INTO được thực thi khi đối tượng mysqli$conn gọi hàm multi_query(). Nếu các câu lệnh SQL thực thi thành công và insert được dữ liệu thì hàm multi_query() sẽ trả về TRUE, ngược lại FALSE.

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

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

// check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
// sql to insert data
$sql = "INSERT INTO gochocit_posts (post_author, post_title, post_content, post_date) 
VALUES ('Vinh Lê', 'Đây là bài số 1', 'Chào tất cả các bạn!', now());";
$sql .= "INSERT INTO gochocit_posts (post_author, post_title, post_content, post_date) 
VALUES ('Phúc Trần', 'Đây là bài số 2', 'Hi everyone!', now());";
$sql .= "INSERT INTO gochocit_posts (post_author, post_title, post_content, post_date) 
VALUES ('Dung Lê', 'Đây là bài số 3', 'Hello all!', now())";
  
if ($conn->multi_query($sql) === TRUE) {
  echo "New records created successfully";
} else {
  echo "Error: " . $sql . "<br>" . $conn->error;
}
  
$conn->close();
?>

2. Thêm (insert) multiple records sử dụng MySQLi (procedural)

Nhiều câu lệnh INSERT INTO được thực thi khi gọi hàm mysqli_multi_query(). Nếu các câu lệnh SQL thực thi thành công và insert được dữ liệu thì hàm mysqli_multi_query() sẽ trả về TRUE, ngược lại FALSE.

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

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

// check connection
if (!$conn) {
  die("Connection failed: " . $conn->connect_error);
}
// sql to insert data
$sql = "INSERT INTO gochocit_posts (post_author, post_title, post_content, post_date) 
VALUES ('Vinh Lê', 'Đây là bài số 1', 'Chào tất cả các bạn!', now());";
$sql .= "INSERT INTO gochocit_posts (post_author, post_title, post_content, post_date) 
VALUES ('Phúc Trần', 'Đây là bài số 2', 'Hi everyone!', now());";
$sql .= "INSERT INTO gochocit_posts (post_author, post_title, post_content, post_date) 
VALUES ('Dung Lê', 'Đây là bài số 3', 'Hello all!', now())";
  
if (mysqli_multi_query($conn, $sql)) {
  echo "New records created successfully";
} else {
  echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
  
mysqli_close($conn);
?>

3. Thêm (insert) multiple records sử dụng PDO (PHP Data Objects)

Từng câu lệnh INSERT INTO được thực thi khi đối tượng PDO$conn gọi hàm exec(). Nếu câu lệnh SQL thực thi thành công và insert được dữ liệu thì hàm exec() không gây ra exception. Ngược lại, hàm exec() sẽ gây ra exception.

Đối tượng $conn gọi hàm beginTransaction() để bắt đầu quá trình insert dữ liêu vào table. Sau đó, hàm commit() được gọi để lưu lại tất cả dữ liệu được insert vào table. Nếu có lỗi trong quá trình insert nhiều record thì sẽ gọi hàm rollback() để hủy tất cả dữ liệu insert vào table.

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

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
  $conn->exec("INSERT INTO gochocit_posts (post_author, post_title, post_content, post_date) 
  VALUES ('Vinh Lê', 'Đây là bài số 1', 'Chào tất cả các bạn!', now())");
  $conn->exec("INSERT INTO gochocit_posts (post_author, post_title, post_content, post_date) 
  VALUES ('Phúc Trần', 'Đây là bài số 2', 'Hi everyone!', now())");
  $conn->exec("INSERT INTO gochocit_posts (post_author, post_title, post_content, post_date) 
  VALUES ('Dung Lê', 'Đây là bài số 3', 'Hello all!', now())");

  // 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;
?>

Khi insert một record và nhiều records vào table trong MySQL thì PHP có các cách xử lý khác nhau. Các bạn cần xác định rõ và sử dụng phù hợp khi cần insert dữ liệu vào table.

5/5 - (1 bình chọn)
Bài trước và bài sau trong môn học<< Thêm (insert) dữ liệu trong MySQL với PHPXóa (delete) dữ liệu trong MySQL với PHP >>
Chia sẻ trên mạng xã hội:

Trả lời

Lưu ý:

1) Vui lòng bình luận bằng tiếng Việt có dấu.

2) Khuyến khích sử dụng tên thật và địa chỉ email chính xác.

3) Mọi bình luận trái quy định sẽ bị xóa bỏ.