MySQL UPDATE查询用于更新 MySQL 数据库中表中的现有记录。
- 它可用于同时更新一个或多个字段。
- 它可用于使用 WHERE 子句指定任何条件。
语法:
更新查询的基本语法是——
UPDATE table_name SET column1=value1,column2=value2, WHERE column_name=col_name
Where更新查询的实现:
让我们考虑下表“数据”,它有四列“ID”、“FirstName”、“LastName”和“Age”。
要更新“数据”表中“ID”为 201 的人的“年龄”,我们可以使用以下代码:
使用程序方法更新查询:
<?php
$link = mysqli_connect("localhost", "root", "", "Mydb");
if($link === false){
die("ERROR: Could not connect. "
. mysqli_connect_error());
}
$sql = "UPDATE data SET Age='28' WHERE id=201";
if(mysqli_query($link, $sql)){
echo "Record was updated successfully.";
} else {
echo "ERROR: Could not able to execute $sql. "
. mysqli_error($link);
}
mysqli_close($link);
?>
输出:
更新后的表 -
Web 浏览器上的输出:
Record was updated successfully.
使用面向对象的方法更新查询:
<?php
$mysqli = new mysqli("localhost", "root", "", "Mydb");
if($mysqli === false){
die("ERROR: Could not connect. "
. $mysqli->connect_error);
}
$sql = "UPDATE data SET Age='28' WHERE id=201";
if($mysqli->query($sql) === true){
echo "Records was updated successfully.";
} else{
echo "ERROR: Could not able to execute $sql. "
. $mysqli->error;
}
$mysqli->close();
?>
输出:
更新后的表 -
Web 浏览器上的输出:
Record was updated successfully.
使用 PDO 方法更新查询:
<?php
try{
$pdo = new PDO("mysql:host=localhost;
dbname=Mydb", "root", "");
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("ERROR: Could not connect. "
. $e->getMessage());
}
try{
$sql = "UPDATE data SET Age='28' WHERE id=201";
$pdo->exec($sql);
echo "Records was updated successfully.";
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. "
. $e->getMessage());
}
unset($pdo);
?>
输出:
更新后的表 -
Web 浏览器上的输出:
Record was updated successfully.