遇到PDO查询问题

时间:2015-05-15 15:37:29

标签: php mysql pdo

有人可以看看这段代码吗?我是PDO方法的新手,由于某种原因,每次提交时都会导致500错误。

我把它缩小到这个:

可能是这部分吗? $hash = $stmt['hash'];

if(empty($response['error'])){
    $stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
 // Bind the parameters to the query
    $stmt->bindParam(':username', $username);
    //Carry out the query
    $stmt->execute();
    $hash = $stmt['hash'];

    $affectedRows = $stmt->rowCount(); // Getting affected rows count
    if($affectedRows != 1){
        $response['error'][] = "No User is related to the Username";
    }
    if(password_verify($password, $hash))
    {
      $_SESSION['username'] = $_POST['username'];
            $_SESSION['userid'] = $stmt['ID'];
    }
    else
    {
      $response['error'][] = "Your password is invalid.";
    }
}

如果您需要更多信息,请询问我会很乐意提供任何我能提供的服务。

2 个答案:

答案 0 :(得分:1)

您需要获取查询结果才能使其可访问。我不确定这是你的问题,我认为$hash只会被设置为资源ID#x,而不是你想要的但不是500.这里是如何获取(http://php.net/manual/en/pdostatement.fetch.php

$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
 // Bind the parameters to the query
    $stmt->bindParam(':username', $username);
    //Carry out the query
    $stmt->execute();
  //if you will only be getting back one result you dont need the while or hashes as an array
   while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
    $hashes[] = $result['hash'];
   }

以下是启用错误报告PHP production server - turn on error messages

的主题

此外,您不必绑定以使用PDO传递值。你也可以做

$stmt = $db->prepare("SELECT * FROM Login WHERE username= ?"); // Prepare the query
$stmt->execute(array($username));

答案 1 :(得分:1)

你的代码非常混乱。只是为了帮助你起点:

if (empty($response['error'])) {
    if (isset($_POST['username'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];
        $stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); 
        $stmt->bindParam(':username', $username);
        $stmt->execute();
        if ($row  = $stmt->fetch(PDO::FETCH_ASSOC)) {
           $hash = $row['hash'];
           if(password_verify($password, $hash)) {
              $_SESSION['username'] = $username;
              $_SESSION['userid'] = $stmt['ID'];
           } else {
              $response['error'][] = "Your password is invalid.";
           }
        } else {
           $response['error'][] = "No User is related to the Username";
        }
    } else {
      $response['error'][] = "Username is not set!";
    }
}