使用 MySQLi 进行更新:
<?php
// 数据库连接参数
$servername = "localhost";
$username = "root";
$password = "your_password";
$database = "your_database";
// 创建连接
$conn = new mysqli($servername, $username, $password, $database);
// 检查连接是否成功
if ($conn->connect_error) {
die("连接失败: " . $conn->connect_error);
}
// 要更新的用户数据
$userId = 1;
$newUsername = "new_username";
$newEmail = "new_email@example.com";
// 执行 UPDATE 语句
$sql = "UPDATE users SET username = '$newUsername', email = '$newEmail' WHERE id = $userId";
if ($conn->query($sql) === TRUE) {
echo "数据更新成功";
} else {
echo "Error updating record: " . $conn->error;
}
// 关闭连接
$conn->close();
?>
使用 PDO 进行更新:
<?php
// 数据库连接参数
$dsn = "mysql:host=localhost;dbname=your_database";
$username = "root";
$password = "your_password";
// 创建 PDO 实例
try {
$conn = new PDO($dsn, $username, $password);
// 设置 PDO 错误模式为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("连接失败: " . $e->getMessage());
}
// 要更新的用户数据
$userId = 1;
$newUsername = "new_username";
$newEmail = "new_email@example.com";
// 执行 UPDATE 语句
$sql = "UPDATE users SET username = :username, email = :email WHERE id = :id";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username', $newUsername, PDO::PARAM_STR);
$stmt->bindParam(':email', $newEmail, PDO::PARAM_STR);
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
if ($stmt->execute()) {
echo "数据更新成功";
} else {
echo "Error updating record: " . $stmt->errorInfo()[2];
}
// 关闭连接
$conn = null;
?>
在这两个示例中,我们使用UPDATE语句来更新用户表(users)中的记录。要更新的数据包括新的用户名(newUsername)和新的电子邮件地址(newEmail)。请注意,为了防止SQL注入攻击,建议使用预处理语句。
转载请注明出处:http://www.pingtaimeng.com/article/detail/3444/PHP