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

报告相同问题?

悬赏问题

  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符