我在数据库中有一些用户,我可以编辑他们的名字和密码但是当我尝试编辑用户名时,查询失败了。
这是我的代码
$user->username = $db->mysql_prep($_POST["username"]);
$user->hashed_password = ($_POST["password"]);
$user->firstname = $db->mysql_prep($_POST["firstname"]);
$user->lastname = $db->mysql_prep($_POST["lastname"]);
$user_query = $user->find_user_by_username($user->username);
$user->id = $user_query["id"];
$result = $user->change_user_by_id($user);
//->id,$user->username,$user->hashed_password,$user->firstname,$user->lastname
unset($user);
我的change_user_by_id方法:
public function change_user_by_id($user){
global $db;
global $session;
$query = "UPDATE users SET ";
$query .= "username = '{$user->username}', ";
$query .= "first_name = '{$user->firstname}', ";
$query .= "last_name = '{$user->lastname}' ";
$query .= "WHERE id = {$user->id} ";
$query .= "LIMIT 1";
$result = mysqli_query($db->connection, $query);
$db->confirm_query($result);
if ($result && mysqli_affected_rows($db->connection) == 1) {
// Success
$session->message("User updated.");
redirect_to("list.php");
} else {
// Failure
$session->message("User update failed.");
}
}
我的find_user_by_username方法:
public static function find_user_by_username($username="default"){
global $db;
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE username = '{$username}' ";
$query .= "LIMIT 1";
$user_set = mysqli_query($db->connection, $query);
$db->confirm_query($user_set);
if($user = mysqli_fetch_assoc($user_set)) {
return $user;
} else {
return null;
}
}
编辑:
我得到的唯一错误来自confirm_query函数我收到消息“数据库查询失败”这是函数:
public function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed.");
}
}
编辑2:
添加了错误消息,这就是我得到的:
您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以便使用正确的语法 在第1行'LIMIT 1'附近
答案 0 :(得分:0)
我认为这是因为使用用户名来获取ID,这意味着更改用户名意味着无法检索到ID。所以我改变了我的代码并在我的表单中为id添加了一个隐藏字段。
旧代码:
$user->username = $db->mysql_prep($_POST["username"]);
$user->hashed_password = ($_POST["password"]);
$user->firstname = $db->mysql_prep($_POST["firstname"]);
$user->lastname = $db->mysql_prep($_POST["lastname"]);
$user_query = $user->find_user_by_username($user->username);
$user->id = $user_query["id"];
$result = $user->change_user_by_id($user);
unset($user);
替换为新代码:
$user->username = $db->mysql_prep($_POST["username"]);
$user->hashed_password = ($_POST["password"]);
$user->first_name = $db->mysql_prep($_POST["first_name"]);
$user->last_name = $db->mysql_prep($_POST["last_name"]);
$user->id = $db->mysql_prep($_POST["id"]);
$result = $user->change_user_by_id($user);
unset($user);