php - 使用 fetchAll() 从 PDO 对象中选择

标签 php mysql pdo

出于某种原因,无论参数是什么以及 SQL 行中的实际内容如何,​​以下代码始终返回 true。它还会引发错误“注意:C:\wamp\www\Social Networking\INC\login.inc 第 7 行中的 0 未定义偏移量”,但我看不出有什么问题:

<?php
function checkAccount($username, $password){
    include("INC/dbconnect.inc");/*"INC/dbconnect.inc" is <?php $pdo = new PDO("mysql:host=localhost;dbname=socialnetwork","user","123"); ?>*/
    $select = $pdo->prepare("SELECT id,password FROM users WHERE user_username = :username");
    $select->execute(array(':username'=>$username));
    $q_rows = $select->fetchAll();
    if($q_rows[0][0]/*the ID of the user, it should always be greater than 1, if not then the username does not exist*/ > 0 && $q_rows[0][0] != null){
        if($q_rows[0][1]/*the password of the user*/ == $password)
            return true;
        else
            return false;
    }
    else
        return false;
    $pdo=null;
} ?>

谁能告诉我哪里出了问题?我已经在代码内部评论了我遇到的问题,并且我尝试了正常的 $select->fetch() 而不是 $select->fetchAll() 到没有有用。在发布此 ( http://php.net/manual/en/pdostatement.fetchall.php ) 之前,我已经阅读了 PDO。这是我文件的其余部分 http://pastebin.com/YCkrRivs , 谢谢。

最佳答案

您不需要使用fetchAll,只需使用fetch:

$q_row = $select->fetch();

if ($q_row) {
  // do your logic ...
}

并且您返回的是字符串 "true"/"false",而不是 bool 值,您应该改用 true/false

更简单,你可以像下面那样做:

$q_row = $select->fetch();
return $q_row && $q_row[0] > 0 && $q_row[1] === $password;

关于php - 使用 fetchAll() 从 PDO 对象中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14026828/

相关文章:

javascript - Woocommerce 产品选项有条件

php - 根据第三表行显示来自两个组合表的数据

php - 如何使用 php mysql 创建每周日自动页面加载?

php - DB PHP 中的条目数

php - 使用 PHP 或 MySQL 转换 utf8 字符

javascript - 如何在不使用 include() 的情况下从不同的 PHP 脚本访问变量

PHP 字符串转 MySQL 日期

mysql - 数据模型: Having separate table for a field vs having it as a column in the main table

php - PDO 准备语句并以 bool 模式进行匹配

php - 无法获取 URL 中的用户名