尝试使用PDO检查用户对数据库

时间:2012-06-02 11:20:11

标签: php mysql class pdo

您好我在提交登录表单后检查用户的用户名和密码,以检查数据库中是否存在使用PDO但是返回false。

以下是我正在使用的代码:

<?php 
//import all of the available functions
require_once('func/functions.php');

//create a connection to the database
$database = new database('localhost', 'root', 'usbw');
$database->connect();
$database->select('mjbox');

//Check if the user is logged in
loggedin();


//Check if the submit button has been clicked first
if ( isset( $_POST['submit'] ) ){
    //Check if user exists on database
    match_login($_POST['username'],$_POST['password']);
}
?>

//Check if user is logged in
function loggedin(){
    //Check if the loggedin status is set to true, meaning that user is logged in.
    if ( isset ( $_SESSION['loggedin'] ) && $_SESSION['loggedin'] == true  ) {
        echo '<p>Hello '. $_SESSION['username'] . ', <a href="Logout.php">Logout.</a></p>';
    }else{
        //If the user is not logged in display a login form
        echo '<form action="index.php" method="post">';
        echo '<input type="text" name="username">';
        echo '<input type="text" name="password">';
        echo '<input type="submit" name="submit" value="submit">';
        echo '<form>';
    }

}

//Check users login details
function match_login($username, $password){
        //If the button has been clicked get the variables
        $dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
        $stmt = $dbh->prepare("SELECT * FROM mjbox WHERE username=':name' AND password=':pword'");
        $stmt->bindParam(":name", $_POST['username']);
        $stmt->bindParam(":pword", $_POST['password']);
        $stmt->execute();

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

            echo 'There is a match!';
        }else{
            echo 'nooooo';
        }
}

这是我第一次尝试使用PDO,我是否正确使用过它?所有细节看起来都是正确的,并且用户存在于数据库中,因此不能解释为什么它不会返回true。 感谢

1 个答案:

答案 0 :(得分:1)

在PDO中绑定字符串会自动为您添加引号。只需在查询中删除引号:name和:pword即可修复它。