HOWTO · PHP
PHP 在 MySQL 表中的 UPDATE 查詢
PHP UPDATE 查詢可以更新 MySQL 表中的現有記錄。
本頁內容
在本教程中,我們將介紹 PHP UPDATE 語句。我們將探討如何使用此語句更新 MySQL 表中的現有記錄。
在 PHP 中使用 mysqli_connect 連線到包含 MySQL 表的資料庫
首先,我們需要了解如何連線到 MySQL 表資料庫。參見示例:
<?php
$user = 'root';
$pass = '';
$db = 'sample tutorial';
//Replace 'sample tutorial' with the name of your database
$con = mysqli_connect("localhost", $user, $pass, $db);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
// Since the output should be blank for a successful connection you can echo `Database Connected `.
echo 'Database Connected';
?>
輸出:
Database Connected
我們的資料庫 sample tutorial 有一個名為 parkinglot1 的表。下面是表格的樣子。
| CarID | BrandName | OwnersName | RegistrationNumber |
|---|---|---|---|
| 1 | Benz | John | KDD125A |
| 2 | Porsche | Ann | KCK345Y |
| 3 | Buggatti | Loy | KDA145Y |
| 4 | Audi | Maggie | KCA678I |
| 5 | Filder | Joseph | KJG998U |
| 6 | Tesla | Tesla | KMH786Y |
假設 John 的汽車的 RegistrationNumber 發生了變化。我們會將註冊號從 KDD125A 更改為 KBK639F。
使用 Update 查詢更新 Mysql 表中的現有記錄
<?php
$user = 'root';
$pass = '';
$db = 'sample tutorial';
//Replace 'sample tutorial' with the name of your database
$con = mysqli_connect("localhost", $user, $pass, $db);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
// Since the output should be blank for a sucessful connection you can echo `Database Connected `.
echo 'Database Connected';
echo '<br>';
//Update
$sql = "UPDATE parkinglot1 SET RegistrationNumber = 'KBK639F' WHERE CarID = 1";
// Check if the update was successful.
if ($con->query($sql) === TRUE){
echo 'Registration Number Updated Successfully';
} else{
echo 'Error Updating the Registration Number:' . $con->error;
}
?>
輸出:
Database Connected
Registration Number Updated Successfully
這是更新後我們的表格的樣子:
| CarID | BrandName | OwnersName | RegistrationNumber |
|---|---|---|---|
| 1 | Benz | John | KBK639F |
| 2 | Porsche | Ann | KCK345Y |
| 3 | Buggatti | Loy | KDA145Y |
| 4 | Audi | Maggie | KCA678I |
| 5 | Filder | Joseph | KJG998U |
| 6 | Tesla | Tesla | KMH786Y |
注意
你應該使用
WHERE 語句指定在何處進行更改,如我們的程式碼所示;否則,你最終可能會更新所有內容。