− Phần này giải thích cách xóa hoặc làm sạch các bản ghi đang tồn tại từ MySQL Database bởi sử dụng PHP.

Dữ liệu có thể bị xóa từ MySQL Table bởi thực thi lệnh SQL DELETE qua hàm mysql_query() trong PHP.

Dưới đây là ví dụ đơn giản để xóa record từ employee table. Để xóa một record trong bất kỳ Table nào, điều cần thiết là xác định vị trí của record đó bởi sử dụng một mệnh đề điều kiện. Ví dụ sau sử dụng key gốc để so khớp một record trong employee table.

Ví dụ

Ví dụ sau minh họa hoạt động delete. Bạn cần cung cấp employee ID để xóa một employee từ employee table.

<html>

   <head>
      <title>Xóa một bản ghi từ MySQL Database</title>
   </head>

   <body>
      <?php
         if(isset($_POST['delete']))
         {
            $dbhost = 'localhost:3036';
            $dbuser = 'tennguoidung';
            $dbpass = 'matkhau';
            $conn = mysql_connect($dbhost, $dbuser, $dbpass);

            if(! $conn )
            {
               die('Không thể kết nối: ' . mysql_error());
            }

            $emp_id = $_POST['emp_id'];

            $sql = "DELETE employee ". "WHERE emp_id = $emp_id" ;
            mysql_select_db('test_db');
            $retval = mysql_query( $sql, $conn );

            if(! $retval )
            {
               die('Không thể xóa dữ liệu: ' . mysql_error());
            }

            echo "Xóa dữ liệu thành công\n";

            mysql_close($conn);
         }
         else
         {
            ?>
               <form method="post" action="<?php $_PHP_SELF ?>">
                  <table width="400" border="0" cellspacing="1" cellpadding="2">

                     <tr>
                        <td width="100">ID</td>
                        <td><input name="emp_id" type="text" id="emp_id"></td>
                     </tr>

                     <tr>
                        <td width="100"> </td>
                        <td> </td>
                     </tr>

                     <tr>
                        <td width="100"> </td>
                        <td>
                           <input name="delete" type="submit" id="delete" value="Delete">
                        </td>
                     </tr>

                  </table>
               </form>
            <?php
         }
      ?>

   </body>
</html>

Viết câu trả lời

Drop Images

0 Bình luận