gpt4 book ai didi

php - MySQLI 更新不起作用且未返回任何错误

转载 作者:行者123 更新时间:2023-11-30 00:38:45 25 4
gpt4 key购买 nike

我正在尝试纠正脚本以更新数据库中的用户,这是我的代码:

我从表单中获取用户数据:

$user = new User();

if (isset($_POST['submit'])) {
// Process the form

// validations
// $required_fields = array("username", "password");
// validate_presences($required_fields);

// $fields_with_max_lengths = array("username" => 30);
// validate_max_lengths($fields_with_max_lengths);

$errors = ""; //temp

if (empty($errors)) {

$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"]);

print_r($user);

$user_by_id = $user->find_user_by_id($user->id);

print_r($user_by_id);

$result = $user->change_user_by_id($user_by_id);

//->id,$user->username,$user->hashed_password,$user->firstname,$user->lastname

unset($user);
}

这是我的 find_user_by_id 方法:

public static function find_user_by_id($id=0){

global $db;

$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE id = {$id} ";
$query .= "LIMIT 1";

$user_set = mysqli_query($db->connection, $query);
$db->confirm_query($user_set);

if($user = mysqli_fetch_object($user_set)) {
return $user;
} else {
return null;
}
}

最后是我的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->first_name}', ";
$query .= "last_name = '{$user->last_name}' ";
$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.");
redirect_to("change.php?id={$user->id}");

}
}

当我尝试更新用户时,我被重定向到change.php,并显示错误消息“用户更新失败”。我一直在试图理清逻辑,但我似乎找不到哪里出了问题。后来添加了 print_r 以查看对象是否具有正确的值,结果确实如此。

编辑1:

我更改了一些代码来查看 mysqli_affected_rows 返回什么,它返回 0。

最佳答案

几个小时后我终于想通了,我只需要把线拿出来:

$user_by_id = $user->find_user_by_id($user->id);

并更改行:

$result = $user->change_user_by_id($user_by_id);

至:

 $result = $user->change_user_by_id($user);

该行是 the way I was doing it before 的剩余部分这导致我将原始数据而不是新数据发送到更改方法。

关于php - MySQLI 更新不起作用且未返回任何错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21959280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com