PHP OOP登录系统:在字段下显示错误

时间:2018-04-16 04:03:18

标签: php html

我正在使用面向对象的PHP创建登录表单。

我得到的问题是我想在字段下输出错误。我收到的错误消息是Uncaught Error: Call to a member function errors()

以下是代码:

conn.php

<?php

class Connection {
    private $DB_HOST = 'localhost';
    private $DB_BASE = 'login_database';
    private $DB_USER = 'root';
    private $DB_PASS = '';
    protected $DB_CONN;

    public function __construct() {
        try {
            $this->DB_CONN = new PDO('mysql:host='.$this->DB_HOST.';dbname='.$this->DB_BASE.';charset=utf8', $this->DB_USER, $this->DB_PASS);
            $this->DB_CONN->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch(PDOException $e) {
            echo $e->getMessage();
        }
    }
}

的login.php

<?php

include('conn.php');

class Login extends Connection {
    private $dbEmail;
    private $dbPassword;
    private $query;
    public $error;

    public function loginFormHandler($email, $password) {
        $this->query = $this->DB_CONN->prepare("SELECT `email`, `password` FROM `users` WHERE `email` = :email AND `password` = :password");
        $this->query->bindParam(':email', $email);
        $this->query->bindParam(':password', $password);
        $this->query->execute();

        while($row = $this->query->fetch(PDO::FETCH_ASSOC)) {
            $this->dbEmail = $row['email'];
            $this->dbPassword = $row['password'];
        }

        if($this->dbEmail === $email && $this->dbPassword === $password) {
            $this->error = 'No errors found.';
        } else {
            $this->error = 'You got an error';
        }
    }

    public function errors() {
        return $this->error;
    }
}

的index.php

<?php

include('class/login.php');

if(isset($_POST['email']) && isset($_POST['password'])) {
    $email = $_POST['email'];
    $password = $_POST['password'];

    if(!empty($email) && !empty($password)) {
        $user = new Login;
        $user->loginFormHandler($email, $password);
    }
}

?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login Form</title>
</head>
<body>
    <div class="form">
        <form action="/oop/index.php" method="POST" accept-charset="UTF-8">
            <label for="email">Email: </label>
            <input type="email" name="email" required>
            <?php echo $user->errors(); ?>
            <label for="password">Password: </label>
            <input type="password" name="password" required>
            <input type="submit" value="Login">
        </form>
    </div>
</body>
</html>

问题在于这一行:<?php $user->errors(); ?>我在index.php的顶部实例化了类并将其分配给变量$user。所以我在$user中使用变量index.php变量。

但看起来我无法使用$user变量。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

问题是您的对象声明,您已在if条件下声明您的对象用户,如果用户提交表单,则该用户将为true。

解决方法是,你必须在if语句之外声明你的对象。

在echo语句

之前,您可以检查是否设置了用户变量