[英]Getting number of rows and data of that row in a single query using PDO in PHP
我有一个登录系统,最初我要检查用户名/密码组合是否正确,然后获取列以设置会话变量
这是我的代码
$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";
希望我对你正确。
尝试全部提取
$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";
fetchColumn()-从结果集的下一行返回单个列 。 它不是像“ select count(*)...”中那样的结果行的数量,而是结果行中(在您的情况下)第一列(uid)的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.