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

Update cơ sở dữ liệu – PHP sử dụng hàm truy vấn mysqli () hoặc mysql_query () để cập nhật 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 để cập nhật 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 cập nhật các bản ghi từ bảng tutorial_tbl đã được tạo ra ở phần trước.

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

Đoạn mã sau sẽ cập nhật các bản ghi vào bảng tutorial_tbl

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

<html>
   <head>
      <title>Updating MySQL Table</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('UPDATE tutorials_tbl set tutorial_title = "Learning Java" where tutorial_id = 4')) {
            printf("Table tutorials_tbl updated successfully.<br />");
         }
         if ($mysqli->errno) {
            printf("Could not update 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 updated 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: 4, Title: Learning Java, Author: Vu Ba Phuong, Date: 10-10-2021
Id: 5, Title: Apache Tutorial, Author: Nguyen Van A, Date: 10-10-2021