如何使用PDO从数据库中获取信息



我正在尝试创建一个登录函数,该函数将根据我存储在数据库中的密码检查密码。如果相关的话,我已经使用phpass在输入密码之前对其进行了散列。到目前为止,这是我的代码;显然,检查将不起作用,因为我还没有从数据库中提取$stored_hash:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL); ini_set('display_errors', 1);
require "/home/carlton/public_html/PHPproject/includes/PasswordHash.php";
if ($_POST){
$form = $_POST;
$username = $form['username'];
$password = $form['password'];
$hash_obj = new PasswordHash(8, false);
$passwordhash = $hash_obj->HashPassword($password);
$storedhash = this is where i need the code to pull the hashed password from the db;
try{
    $db = new PDO('mysql:host=localhost;dbname=phpproject', 'carl', 'pdt1848?');
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
    catch(PODException $e){
        echo "Can't connect to the database";
    }
$query=$db->prepare("SELECT password FROM users WHERE username=$username");

$check = CheckPassword($password, $stored_hash);
if($check){
    print_r("Registered user");
}
else{
    print_r("Not a registered user");
}

//login here
}
else{
?>
<form name="login" action="login.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<button type="submit">Submit</button>
<button type="reset">Reset Form</button>
</form>
<?php
}
?>

尝试这个快速解决方案:

<?php
ini_set('display_errors', 1);
error_reporting(E_ALL); ini_set('display_errors', 1);
require "/home/carlton/public_html/PHPproject/includes/PasswordHash.php";
if ($_POST){
$form = $_POST;
$username = $form['username'];
$password = $form['password'];
$hash_obj = new PasswordHash(8, false);
$passwordhash = $hash_obj->HashPassword($password);
$db = new PDO('mysql:host=localhost;dbname=phpproject', 'carl', 'pdt1848?');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$response = $bdd->query("SELECT password FROM users WHERE username='".$username."'");
$data=$response->fetch();
$stored_hash = $data['password'];
echo '<br>the password stored in the database is :'. $stored_hash.'<br>';
$check = CheckPassword($password, $stored_hash);
if($check){
    print_r("Registered user");
}
else{
    print_r("Not a registered user");
}

//login here
}
else{
?>
<form name="login" action="login.php" method="POST">
<label for "username">Username: </label>
<input type="text" name="username"/><br />
<label for "password">Password: </label>
<input type="password" name="password"/><br />
<button type="submit">Submit</button>
<button type="reset">Reset Form</button>
</form>
<?php
}
?>

最新更新