使用PHP中的PDO在单个查询中获取行数和该行的数据 [英] Getting number of rows and data of that row in a single query using PDO in PHP
问题描述
我有一个登录系统,最初我要检查用户名/密码组合是否正确,然后获取列以设置会话变量
I have a log-in system where initially I am checking whether the username/password combination is correct and then fetching the columns to set session variables
这是我的代码
$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个库仑),而如果$sql
具有曾经
1) fetchColumn()
is giving wrong result as 3 (though I have single row matching that parameters and 15 coulmns per row) whereas if the $sql
had been
$sql='select count(*) from users where username=? and password=?';
给出正确答案为 1 为什么?
gives correct answer as 1 Why?
2)我看到了php手册,发现rowCount()
仅适用于DML查询,它建议
2) I saw the php manual and I found that rowCount()
is gauranteed only for DML queries and it suggests workaround for SELECT but it costs 2 queries per login.
有没有一种方法可以使用单个查询?
Is there a way I can do using single query?
编辑
现在我正在使用类似的东西,它似乎工作正常,但问题很少.请参阅评论
Now I am using something like this and it seems to work fine but few problems .see comments
$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";
推荐答案
希望我对此有所了解.
尝试全部提取
$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";
这篇关于使用PHP中的PDO在单个查询中获取行数和该行的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!