mysql行计数查询不起作用

时间:2013-01-12 22:27:03

标签: php mysql

我认为我的问题出现在我的代码的MySQL部分中,我需要将至少一个表行计为真,并继续if语句,否则执行else语句。当我运行代码时,除了页面顶部的用户名和密码echo之外,它不显示错误只是一个空白页面我只是检查它们是否正在通过而且它们是。我的代码如下:

<?php

$myusername=$_POST['userName']; 
$mypassword=$_POST['password']; 

echo $mypassword;
echo "<br>" . $myusername;

$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

try {
    $conn = new PDO('mysql:host=localhost;dbname=timecard', 'username', 'password');
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $conn->prepare('SELECT COUNT(*) FROM employees WHERE `userName`= :userName AND `password`= :password');

    $stmt->execute(array(':userName' => $myusername, ':password' => $mypassword));

    } catch(PDOException $e){
        echo'ERROR: ' . $e->getMessage();
    }

$res = $conn->query($stmt);

if($res->fetchColumn() > 0){


session_register("myusername");
session_register("mypassword"); 
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>

1 个答案:

答案 0 :(得分:3)

管理PDO语句的方式有问题(参见文档http://php.net/manual/en/pdostatement.fetchcolumn.php)。删除包含以下内容的行:

$res = $conn->query($stmt);

并替换:

if($res->fetchColumn() > 0){

by:

if ($stmt->fetchColumn() > 0) {