duandushang5148
2014-10-03 16:00
浏览 38
已采纳

在SQL语句中使用OR,在PHP中给出“未定义的变量”错误

I'm grabbing a count stat ($hits) from the following sql statement:

SELECT COUNT(*) AS hits FROM users 
    WHERE password = :password
    AND username = :username

Grabbing the variable in a while() loop here works fine, it's not untill I try this:

SELECT COUNT(*) AS hits FROM users 
    WHERE password = :password
    AND (username = :username OR email = :username)

that I get an 'undifined variable' error when I try pull 'hits' as $hits = $row['hits'];

I want a user to be able to log in using a username or email address. Can anyone tell me why the first SQL statement works fine but the second does not?

My PHP is as follows:

// COUNT HITS
$COUNT_HITS = $DBH->prepare("SELECT COUNT(*) AS hits FROM users WHERE password = :password AND (username = :username OR email = :username)");
$COUNT_HITS->bindParam(':password', $password);
$COUNT_HITS->bindParam(':username', $username);
$COUNT_HITS->execute();
while($row = $COUNT_HITS->fetch(PDO::FETCH_ASSOC)){
    $hits= $row['hits'];
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

  • douchui1657 2014-10-03 17:59
    最佳回答

    Problem

    Look here:

    username = :username OR email = :username

    You can do this in PDO, not by default at least

    Solution

    Add a third params

    username = :username OR email = :username_email

    and bind to the same $username value, that's okay.

    $COUNT_HITS->bindParam(':password', $password);
    $COUNT_HITS->bindParam(':username', $username);
    $COUNT_HITS->bindParam(':username_email', $username);
    $COUNT_HITS->execute();
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题