0

我正在尝试使用 PDO 在我的网站上创建登录部分。

到目前为止,我有以下...

配置文件

    // Connect to DB
    $username = 'user@site.co.uk';
    $password = 'pass';

    try {
        $conn = new PDO('mysql:host=localhost;dbname=db', $username, $password);    
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } 
    catch(PDOException $e) {
        echo 'ERROR: ' . $e->getMessage();
        }

?>

头文件.php

// DB Config
include '/assets/config.php';

// User Session
$login = 'liam';
$pass = 'password';

$sth = $conn->prepare("SELECT * FROM access_users WHERE login = ? AND pass = ?");
$sth->bindParam(1, $login);
$sth->bindParam(2, $pass);
$sth->execute();

if ($sth->rowCount() > 0)
{
  // session stuff,
 // refresh page
}  

?>

但是,我的浏览器不显示该页面,并且当我查看我的源代码时,其中没有包含任何数据,任何人都可以看到我哪里出错了吗?

4

2 回答 2

1

你已经设置了PDO::ERRMODE_EXCEPTION。这意味着,您应该将语句包装在一个try/catch块中并测试execute()返回代码:

try {
    $sth = $conn->prepare("SELECT * FROM access_users WHERE login = ? AND pass = ?");
    $sth->bindParam(1, $login);
    $sth->bindParam(2, $pass);
    if (!$sth->execute()) {
        $info = $sth->errorInfo();
        echo 'Error: ' . $sth->errorCode() . ' (' . $info[2] . ")\n";
    } elseif ($sth->rowCount() > 0)
    {
        // session stuff,
        // refresh page
    }
} catch (PDOException $e) {
    echo 'Exception: ' . $e->getMessage() . "\n";
}

当然,还要放入一些跟踪语句。

于 2012-11-10T22:51:26.010 回答
1

尝试这个:

// User Session
$login = 'liam';
$pass = 'password';
$sth = $conn->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$sth->execute(array(":username" => $login,":password" => $pass));

if ($sth->rowCount() > 0)
{
// session stuff,
// refresh page
  echo $sth->rowCount();
} 

确保您有用户名“liam”并在数据库中传递“密码”

于 2012-11-10T12:16:55.930 回答