简体   繁体   English

使用PHP和PDO登录用户时遇到麻烦

[英]Having trouble logging a user in using PHP and PDO

From the PDO manual: 从PDO手册中:

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

I have this code: 我有以下代码:

<?php

require 'core.inc.php';

if(isset($_POST['user']) AND isset($_POST['pass'])){

    if(!empty($_POST['user']) AND !empty($_POST['pass'])){
        $user = $_POST['user'];
        $pass = $_POST['pass'];
            require 'connect.inc.php';
            $st = $db_pdo->prepare("SELECT id FROM users WHERE user=? AND pass=?");
            $st->bindParam(1, $user);
            $st->bindParam(2, $pass);
            $st->execute();
            $result = $st->fetchColumn();
                if($st->rowCount() > 0){
                   $id_arr = $st->fetch();
                   $id = $id_arr[0];
                   $_SESSION['user_id'] = $id;
                   header('Location: edit.php');
                    } else { echo 'Username or password incorrect';}

    } else { echo 'You must fill in all fields.';}
}
?>

The number of rows returned is always 0, as stated in the manual. 如手册中所述,返回的行数始终为0。 No surprise there. 毫不奇怪。

1) I want to log a user in and set his $_SESSION id to his user ID from a db. 1)我想登录一个用户,并将他的$ _SESSION ID设置为来自数据库的用户ID。

2) I suck so much at PDO it's not even funny, I can't figure out what function to use to log the user in. If the number or rows is always 0, clearly the Username or password incorrect will appear all the time. 2)我对PDO感到非常厌烦,这甚至都不是一件好事,我无法弄清楚该使用什么功能登录用户。如果数字或行始终为0,则很明显,用户名或密码始终会出现错误。

Try this : 尝试这个 :

try 

 {
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO('mysql:host='.$host.';dbname=' . $dbname, $dbuser, $dbpassword, $pdo_options);

$request = $bdd->prepare('SELECT id FROM users WHERE user = :user AND pass = :password');
$request->execute(array('user' => $_POST['user'],                                               
                        'password' => $_POST['pass']                  
                                                    ));

$data = $request->fetch();

if ($data)
    {
         session_start();
         $_SESSION['ID'] = $data['id'];
         //you can run other verification here if you want
         header('Location: edit.php');

    }
else 
    { 
        echo 'Username or password incorrect';
    }
$requete->closeCursor();

}

catch(Exception $erreur)

   {
      die('Login error : '.$erreur->getMessage());
   }

Hope that helps . 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM