UPDATE 语句用于中修改数据库表中的数据。
更新数据库中的数据
UPDATE 语句用于更新数据库表中已存在的记录。
语法
UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value
注释:请注意 UPDATE 语法中的 WHERE 子句。WHERE 子句规定了哪些记录需要更新。如果您想省去 WHERE 子句,所有的记录都会被更新!
如需学习更多关于 SQL 的知识,请访问我们的 SQL 教程。
下面的实例将从 "myguests" 表中选取所有 email='john@example.com' 的行并更新firstname值:
使用 MySQLi
MySQLi - 面向对象:
实例
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "mydb";
// 创建连接
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
$sql = "UPDATE myguests SET firstname = ? WHERE email = ?";
//创建预处理语句
$stmt = $conn->prepare($sql);
$email = 'john@example.com';
$firstName = 'John2';
//绑定参数
$stmt->bind_param("ss", $firstName,$email);
//执行查询
$stmt->execute();
$conn->close();
?>
MySQLi - 面向过程:
实例
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "mydb";
// 创建连接
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
$sql = "UPDATE myguests SET firstname = ? WHERE email = ?";
$email = 'john@example.com';
$firstName = 'John2';
$stmt = mysqli_prepare($conn, $sql);
//绑定参数
mysqli_stmt_bind_param($stmt, "ss", $firstName,$email);
//执行SQL
mysqli_stmt_execute($stmt);
mysqli_close($conn);
?>
使用 PDO (+ 预处理)
以下实例使用了预处理语句更新数据。
实例
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "mydbpdo";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "UPDATE myguests SET firstname = :firstname WHERE email = :email";
$stmt = $conn->prepare($sql);
$stmt->execute([':firstname' => 'John2',':email' => 'john@example.com']);
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
分享笔记