php - PHP中的查询不会提取系统中已经存在的数据
问题描述
我正在尝试检查数据库中是否存在给定的电子邮件,但返回的查询为空,我不知道为什么。
我已尝试手动输入表格中记录的电子邮件地址,但仍然无法正常工作。
用户.php:
function emailExists()
{
$query = "SELECT id, firstname, lastname, access_level, password,
status from " . $this->table_name . " where email = ?";
//prepare this query
$stmt = $this->conn->prepare($query);
登录.php:
//get database connection
$database = new Database();
$db = $database->getConnection();
//initialize objects
$user = new User($db);
//check if email and password are in the database
$user->email=$_POST['email'];
//check if email exists, also get user details using this emailExists() method
$email_exists = $user->emailExists();
数据库类:
class Database{
// specify your own database credentials
private $host = "localhost";
private $db_name = "games_for_sale";
private $username = "root";
private $password = "";
public $conn;
// get the database connection
public function getConnection(){
$this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
用户等级:
class User{
//database connection
private $conn;
private $table_name = "users";
//object properties
public $id;
public $firstname;
public $lastname;
public $email;
public $contact_number;
public $address;
public $password;
public $access_level;
public $access_code;
public $status;
public $created;
public $modified;
//constructor
public function _construct($db){
$this->conn = $db;
}
//check if given email exist in the database
function emailExists()
{
$query = "SELECT id, firstname, lastname, access_level, password, status from " . $this->table_name . " where email = ?";
//prepare this query
$stmt = $this->conn->prepare($query);
//sanitize
$this->email = htmlspecialchars(strip_tags($this->email));
//bind given email value
$stmt->bindParam(1, $this->email);
//execute the query
$stmt->execute();
//get number of rows
$num = $stmt->rowCount();
//if email exists, assign values to object properties for easy access and use for php sessions
if ($num > 0) {
//get record details / values
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//assign values to object properties
$this->id = $row['id'];
$this->firstname = $row['firstname'];
$this->lastname = $row['lastname'];
$this->access_level = $row['access_level'];
$this->password = $row['password'];
$this->status = $row['status'];
//return true because email exists in the database
return true;
}
//retturn false if email does not exist in the database
return false;
}
}
我得到的错误:
致命错误:未捕获错误:在 user.php:34 中调用成员函数 prepare() 堆栈跟踪:
#0 login.php(34): User->emailExists()
#1 {main} 在 user.php 中抛出在第 34 行