小编典典

使用PHP中的PDO在单个查询中获取行数和该行的数据

sql

我有一个登录系统,最初我要检查用户名/密码组合是否正确,然后获取列以设置会话变量

这是我的代码

$sql='select uid,name from users where username=? and password=?';
$query=$con->prepare($sql);
$result=$query->execute(array($username,$password));
$query->setFetchMode(PDO::FETCH_ASSOC);

//check if a single row is returned

if(($query->fetchColumn())===1)
    {
        //set session variables
        header('Location: lading_page.php');
    }
else echo "Invalid username/password";

1) fetchColumn()是给错误的结果为 3 (虽然我有单列匹配该参数和每行15个coulmns),而如果$sql已经

$sql='select count(*) from users where username=? and password=?';

给出正确答案为 1 为什么?

2)
我看到了php手册,发现它rowCount()仅适用于DML查询,并且建议使用SELECT的解决方法,但每次登录花费2个查询。

有没有一种方法可以使用单个查询?

编辑

现在我正在使用类似的东西,它似乎可以正常工作,但几乎没有问题。请参阅评论

$sql='select uid,name from users where username=? and password=?';
$query=$con->prepare($sql);
$result=$query->execute(array($username,$password));

$rows= $query->fetchAll(PDO::FETCH_ASSOC);
if(count($rows)===1)
    {
          //I reached here
        echo $_SESSION['id']=$rows['uid']; //undefined index uid
        echo $_SESSION['name']=$rows['name'];//undefined index name
        //header('Location: landing_page.php');
    }
else $error="Invalid username/password";

阅读 161

收藏
2021-05-16

共1个答案

小编典典

希望我对你正确。

尝试全部提取

$rows = $query->fetchAll(PDO::FETCH_ASSOC);

在你的情况下

$sql='select uid,name from users where username=? and password=?';
$query=$con->prepare($sql);
$result=$query->execute(array($username,$password));


// check if a single row is returned
// i guess to avoid the warnings you can just set the array befor like
// $row = array();
// or put @ befor the VARS in the TRUE statement

$rows = $query->fetchAll(PDO::FETCH_ASSOC));

/** 
if you have more than one result you can look at them like this

foreach ($rows as $row)
{
    echo $row['uid'];
}
**/

if((count($rows)===1)
    {
        echo $_SESSION['id']=@$rows['uid']; 
        echo $_SESSION['name']=@$rows['name'];
        // header('Location: lading_page.php');
    }
else echo "Invalid username/password";
2021-05-16