我正在将登录表单重新编写为基于OOP的PDO。我遇到了上面给出的错误。所以我有两个文件,一个是 login.php ,一个是包含的文件,名为 functions.inc.php
login.php 的代码如下。
<?php
include_once("includes/functions.inc.php");
// get username and password from $_POST
if(!empty($_POST)){
$username = $_POST['email'];
$password = $_POST['password'];
// check if a user can login (function)
if(canilogin($username, $password)){
session_start();
$_SESSION['username'] = $username;
$_SESSION['loggedin'] = true;
header('Location: index.php');
}
else{
$error = true;
// if no -> $error tonen
}
}
?><!DOCTYPE html>
<html lang="en">
<body class="login">
<div class="grid container_login">
<div class="login_grid">
<form class="form_login" action="" method="post">
<?php if( isset($error) ): ?>
<div class="form__error">
<p>
Sorry, we can't log you in with that email address and password. Can you try again?
</p>
</div>
<?php endif;?>
<div>
<label for="email">EMAIL</label><br/>
<input type="text" id="email" name="email" placeholder="Lucasdebelder@snapshot.be" required>
</div>
<div>
<label for="password">PASSWORD</label><br/>
<input type="password" id="password" name="password" placeholder="Atleast 8 characters" required>
</div>
<div>
<input type="submit" value="LOG IN" class="btn_login">
</div>
<p class="center_align">Or</p>
<br/>
<a class="center_align" href="register.php">Register here.</a>
</form>
</div>
</body>
</html>
发生错误的 functions.inc.php ,确切地说,它发生在if($result->num_rows != 1){
。
前几行是曾经工作过的,但是用真正的转义字符串来防止SQL注入,但它有点古怪,我决定尝试将它重新编写为PDO。
<?php
function canilogin( $username, $password){
/* THIS IS THE OLD WAY THAT WORKED/WORKS
$conn = new mysqli("localhost", "root", "root", "snapshot");
$query = "select * FROM users WHERE email='".$conn->real_escape_string($username). "'";
$result = $conn->query($query);
*/
$conn = new PDO('mysql:host=localhost; dbname=snapshot', 'root', 'root');
//$query = "select * FROM users WHERE email='".$conn->real_escape_string($username). "'";
$statement = $conn->prepare("select * from users where email = :username");
$statement->bindValue(':username', $username);
$statement->execute();
$result = $statement->execute();
if($result->num_rows != 1){
return false;
}
$user = $result->fetch_assoc();
if(password_verify($password, $user['password'])){
return true;
}
else{
return false;
}
}
?>
答案 0 :(得分:0)
您遇到此问题的原因是$result
不正确。执行$statement->execute();
后,它将成为PDOStatement
个对象。
首先删除$result = $statement->execute();
并尝试
if($statement->rowCount() != 1){
return false;
}
$user = $statement->fetch();
if(password_verify($password, $user['password'])){
return true;
}
else{
return false;
}