如何用PDO编写这个mysql查询

时间:2014-10-01 13:12:29

标签: php mysql login pdo

我正在编写一个php登录表单,我想使用PDO进行数据库连接并编写查询。实际上我对PDO语句很新,但为了避免sql注入,我宁愿使用它。我很感激有人可以帮我用PDO重写我的查询吗?

这是我的代码:

$qry="SELECT * FROM member WHERE username='$username' AND password='$password'";
$result=mysql_query($qry);

//Check whether the query was successful or not
if($result) {
    if(mysql_num_rows($result) > 0) {
        //Login Successful
        session_regenerate_id();
        $member = mysql_fetch_assoc($result);
        $_SESSION['SESS_MEMBER_ID'] = $member['mem_id'];
        $_SESSION['SESS_FIRST_NAME'] = $member['username'];
        $_SESSION['SESS_LAST_NAME'] = $member['password'];
        session_write_close();
        header("location: home.php");
        exit();
    }else {
        //Login failed
        $errmsg_arr[] = 'user name and password not found';
        $errflag = true;
        if($errflag) {
            $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
            session_write_close();
            header("location: index.php");
            exit();
        }
    }
}else {
    die("Query failed");
}

我试过

$stmt = $conn->prepare("SELECT * FROM member WHERE username = :username and password = :password");` 

$stmt->execute(array(':username' => $username, ':password' => $password));` 

但我不知道如何重写与&#34相关的部分;检查查询是否成功"

2 个答案:

答案 0 :(得分:2)

您可以在这种情况下使用rowCount()来检查:

$stmt = $conn->prepare("SELECT * FROM member WHERE username = :username and password = :password");
$stmt->execute(array(':username'=>$username,':password'=>$password));
if($stmt->rowCount() > 0) {
    // then select row has round rows
    $member = $stmt->fetch(PDO::FETCH_ASSOC);
    session_regenerate_id();
    $_SESSION['SESS_MEMBER_ID'] = $member['mem_id'];
    $_SESSION['SESS_FIRST_NAME'] = $member['username'];
    $_SESSION['SESS_LAST_NAME'] = $member['password'];
    session_write_close();
    header("location: home.php");
    exit();

}

答案 1 :(得分:2)

尝试 -

$stmt = $conn->prepare("SELECT * FROM member WHERE username = :username and password = :password");
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $password);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_OBJ);

if (!empty($result)) {

    # Login Successful    
    $_SESSION['SESS_MEMBER_ID'] = $result->mem_id;
    $_SESSION['SESS_FIRST_NAME'] = $result->username;
    $_SESSION['SESS_LAST_NAME'] = $result->password;

    header("location: home.php");

} else {

    # Login failed
    $errmsg_arr[] = 'user name and password not found';
    $errflag = true;

        if($errflag) {
        $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
        header("location: index.php");
        }

}

请注意,对于插入,更新,删除等,您可以使用$count = $stmt->rowCount();后跟if ($count > 0),但截至目前,SELECT

无法正常执行