我正在创建一个登录页面,检查数据库中的匹配值,如果SELECT查询返回一个带有用户名和密码的匹配行,那么它将返回一个行数1.当我回显时,我现在编码的方式存储行数的变量由于某种原因会回显26,我不确定原因。
有人会解释我是做错了什么,或者这是否是正常行为以及该值来自何处?
function checkLogin($conn,$myusername,$mypassword,$row,$row1){
try {
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
if($results->fetchColumn() > 0) {
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
$rowCount = count($row);
echo $rowCount;
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
echo $count;
}
else {
print "NO ROWS";
}
}
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
答案 0 :(得分:2)
您的代码$rowCount = count($row);
正在计算当前行中的列 - 而不是查询返回的行数。
在同一个注释中,您正在回显第二个 count 相关变量$count
,但您既不会在代码中声明它也不会增加它。看起来这个人应该计算你循环的行数。如果是这样,您应该在循环之前将其设置为$count = 0;
并在其中使用$count++;
:
$count = 0;
foreach ($conn->query($sql) as $row) {
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
$count++;
}
echo $count;
此外,您在选择用户之前正在使用PDO的rowCount
,并且您正在正确使用它。您可以将 结果存储到变量中,并使用它来告知您接收的行数:
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
$numRows = $results->fetchColumn();
if($numRows > 0) {
... rest of your code ....
答案 1 :(得分:1)
function checkLogin($conn,$myusername,$mypassword,$row,$row1)
{
try
{
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql))
{
$count = $results->fetchColumn();
echo "$count\n";
if($count > 0)
{
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
}
else
{
print "NO ROWS";
}
}
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}