Delete cơ sở dữ liệu – PHP & MySQL

Delete cơ sở dữ liệu – PHP sử dụng hàm truy vấn mysqli () hoặc mysql_query () để xóa các bản ghi trong bảng MySQL. Hàm này nhận hai tham số và trả về TRUE nếu thành công hoặc FALSE nếu thất bại.

Cú pháp

$mysqli->query($sql,$resultmode)
STTMô tả thông số
1$sql
Bắt buộc – Truy vấn SQL để xóa các bản ghi trong bảng MySQL.
2$resultmode
Tùy chọn – Hằng số MYSQLI_USE_RESULT hoặc MYSQLI_STORE_RESULT tùy thuộc vào hành động mong muốn kết quả của bạn. Theo mặc định, MYSQLI_STORE_RESULT được sử dụng.

Chương trình sau đây là một ví dụ đơn giản sẽ chỉ ra cách xóa các bản ghi từ bảng tutorial_tbl đã được tạo ra ở phần trước.

Ví dụ Delete cơ sở dữ liệu

Đoạn mã sau sẽ xóa bản ghi trong bảng tutorial_tbl

Sao chép và dán ví dụ sau vào file mysql_example.php

<html>
   <head>
      <title>Deleting MySQL Table record</title>
   </head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $dbname = 'TUTORIALS';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
         
         if($mysqli->connect_errno ) {
            printf("Connect failed: %s<br />", $mysqli->connect_error);
            exit();
         }
         printf('Connected successfully.<br />');
         if ($mysqli->query('DELETE FROM tutorials_tbl where tutorial_id = 4')) {
            printf("Table tutorials_tbl record deleted successfully.<br />");
         }
         if ($mysqli->errno) {
            printf("Could not delete record from table: %s<br />", $mysqli->error);
         }
         $sql = "SELECT tutorial_id, tutorial_title, tutorial_author, submission_date FROM tutorials_tbl";
		 
         $result = $mysqli->query($sql);
         if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
               printf("Id: %s, Title: %s, Author: %s, Date: %d <br />", 
                  $row["tutorial_id"], 
                  $row["tutorial_title"], 
                  $row["tutorial_author"],
                  $row["submission_date"]);               
            }
         } else {
            printf('No record found.<br />');
         }
         mysqli_free_result($result);
         $mysqli->close();
      ?>
   </body>
</html>

Dữ liệu đầu ra

Truy cập vào mysql_example.php được thực thi trên máy chủ web apache và kết quả đầu ra.

Connected successfully.
Table tutorials_tbl record deleted successfully.
Id: 1, Title: MySQL Tutorial, Author: Vu Ba Phuong, Date: 10-10-2021
Id: 2, Title: HTML Tutorial, Author: Vu Ba Phuong, Date: 10-10-2021
Id: 3, Title: PHP Tutorial, Author: Vu Ba Phuong, Date: 10-10-2021
Id: 5, Title: Apache Tutorial, Author: Nguyen Van A, Date: 10-10-2021