我是PHP和SQL的新手,此刻,我只是在学习和试验,并不担心安全性。我正在尝试根据用户ID更新用户名和电子邮件。我的表名是“用户”,该表中的列是“ id,用户名,电子邮件,密码”。
现在查询不执行,这是我到目前为止所做的。
<?php
include("db_connect.php");
error_reporting(0);
$email = $_POST['email'];
$username= $_POST['username'];
$id = $_POST['id'];
$sql= "UPDATE users SET username= '.$username.' , email= '.$email.' WHERE id='.$id.' ";
if($_POST['submit']){
if (mysqli_query($connection, $sql)) {
echo "<h3><center>User information Updated successfully</center></h3>";
}
else {
echo " Something went wrong ";
}
}
?>
<html>
<head>
<title>Add Data</title>
</head>
<body>
<form action="update.php" method="POST" style="font-size: 24px; margin-left: 50px;">
<h4> update user info</h4>
Username: <input type="text" name="username" required><br><br>
Email: <input type="email" name="email" required><br><br>
<input style="background:#2CDC10; font-size:18px;" type="submit" name="submit" value="update data"/>
</form>
</html>
答案 0 :(得分:2)
您的主要问题是您在SQL字符串中使用PHP串联语法。这会使所有值都不正确,因此id
子句中的where
与任何记录都不匹配,因此不会更新任何记录。您的查询应该是
$sql= "UPDATE users SET username= '$username' , email= '$email' WHERE id='$id' ";
或
$sql= "UPDATE users SET username= '" .$username. "' , email= '" . $email . "' WHERE id='" .$id. "' ";
该命令可以运行,但可以进行SQL注入。您应该使用准备好的语句,对其进行参数化,然后使用错误报告:
error_reporting(1);
if(isset($_POST['submit']){
$email = $_POST['email'];
$username= $_POST['username'];
$id = $_POST['id'];
$sql= "UPDATE users SET username=?, email=? WHERE id=?";
$stmt = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt, "ssi", $username, $email, $id);//third i assumes "id" is an integer
$result = mysqli_stmt_execute($stmt);
if(!empty($result)) {
echo "<h3><center>User information Updated successfully</center></h3>";
} else {
printf("Error: %s.\n", mysqli_stmt_error($stmt));
}
}
这是未经测试的粗略答案。有关准备好的语句的更多信息,请参见http://php.net/manual/en/mysqli.quickstart.prepared-statements.php。