簡體   English   中英

使用PHP和PDO登錄用戶時遇到麻煩

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

從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.

我有以下代碼:

<?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.';}
}
?>

如手冊中所述,返回的行數始終為0。 毫不奇怪。

1)我想登錄一個用戶,並將他的$ _SESSION ID設置為來自數據庫的用戶ID。

2)我對PDO感到非常厭煩,這甚至都不是一件好事,我無法弄清楚該使用什么功能登錄用戶。如果數字或行始終為0,則很明顯,用戶名或密碼始終會出現錯誤。

嘗試這個 :

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());
   }

希望能有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM