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条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制