MySQLI更新无法正常工作且未返回任何错误

时间:2014-02-22 19:24:29

标签: php mysql mysqli

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

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

$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.

1 个答案:

答案 0 :(得分: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的残余,它导致我将原始数据而不是新数据发送到更改方法。