如何处理表单中的错误使用pdo类

时间:2018-05-14 10:42:39

标签: php mysqli pdo

我是php的新手,将来会成为超级编码器:) 我正在尝试学习如何使用类,我下载了一个用户类的美国:

loginform.php - > login.php -> validate.php -> user.class.php 

我需要创建3个页面才能进行登录工作。 所以,我通过这种方式将其更改为login.php中的所有内容。 但是无法处理表单中的错误,错误显示在空白页面中,我想显示错误属于输入值。 我知道如何在查询中处理它们,但无法锻炼如何使用函数处理它们。

示例:

   <input type="text" name="username" id="username" class="form-control">
   <span class="help-block">Errors here</span>

这是我在login.php中的php代码:

    require_once 'class/user.php';
    require_once 'config.php';


if($_SERVER["REQUEST_METHOD"] == "POST"){

    $email = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_EMAIL);
    $password = filter_input(INPUT_POST, 'password', FILTER_DEFAULT);

检查用户名是否为空

if(empty(trim($_POST["username"]))){
    $username_err = 'Please enter username.';
} else{
    $username = trim($_POST["username"]);
}

检查密码是否为空

if(empty(trim($_POST['password']))){
    $password_err = 'Please enter your password.';
} else{
    $password = trim($_POST['password']);
}

验证凭据

  if(empty($username_err) && empty($password_err)){

用于功能的USaqe,调用登录功能

if($user->login($email, $password)) {
    header("location: user.php");
} else {
    $user->printMsg();
    die;
}
}

}

Hmtl参与login.php

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
    <div class="form-group">
        <label>Password</label><label>Username</label>
        <input type="text" name="username" id="username" class="form-control">
        <span class="help-block">Errors Here</span>
    </div>    
    <div class="form-group">
        <label>Password</label>
        <input type="password" name="password" class="form-control">
        <span class="help-block">Errors Here</span>
    </div>
    <div class="form-group">
        <input type="submit" name="submit" class="btn btn-primary" value="submit">
    </div>
    <p>Don't have an account? <a href="register.php">Sign up now</a>.</p>
</form>

我的user.class.php

class User{
    /** @var object $pdo Copy of PDO connection */
    private $pdo;
    /** @var object of the logged in user */
    private $user;
    /** @var string error msg */
    private $msg;
    /** @var int number of permitted wrong login attemps */
    private $permitedAttemps = 5;

    /**
    * Connection init function
    * @param string $conString DB connection string.
    * @param string $user DB user.
    * @param string $pass DB password.
    *
    * @return bool Returns connection success.
    */
    public function dbConnect($conString, $user, $pass){
        if(session_status() === PHP_SESSION_ACTIVE){
            try {
                $pdo = new PDO($conString, $user, $pass);
                $this->pdo = $pdo;
                return true;
            }catch(PDOException $e) { 
                $this->msg = 'Connection did not work out!';
                return false;
            }
        }else{
            $this->msg = 'Session did not start.';
            return false;
        }
    }

    /**
    * Return the logged in user.
    * @return user array data
    */
    public function getUser(){
        return $this->user;
    }

    /**
    * Login function
    * @param string $email User email.
    * @param string $password User password.
    *
    * @return bool Returns login success.
    */
    public function login($email,$password){
        if(is_null($this->pdo)){
            $this->msg = 'Connection did not work out!';
            return false;
        }else{
            $pdo = $this->pdo;
            $stmt = $pdo->prepare('SELECT id, fname, lname, email, wrong_logins, password, user_role FROM users WHERE email = ? and confirmed = 1 limit 1');
            $stmt->execute([$email]);
            $user = $stmt->fetch();

            if(password_verify($password,$user['password'])){
                if($user['wrong_logins'] <= $this->permitedAttemps){
                    $this->user = $user;
                    session_regenerate_id();
                    $_SESSION['user']['id'] = $user['id'];
                    $_SESSION['user']['fname'] = $user['fname'];
                    $_SESSION['user']['lname'] = $user['lname'];
                    $_SESSION['user']['email'] = $user['email'];
                    $_SESSION['user']['user_role'] = $user['user_role'];
                    return true;
                }else{
                    $this->msg = 'This user account is blocked, please contact our support department.';
                    return false;
                }
            }else{
                $this->registerWrongLoginAttemp($email);
                $this->msg = 'Invalid login information or the account is not activated.';
                return false;
            } 
        }
    }
}

这是我的connect.php

session_start();
define('conString', 'mysql:host=localhost;dbname=test2');
define('dbUser', 'root');
define('dbPass', '');


define('userfile', 'user.php');
define('loginfile', 'validate.php');
define('activatefile', 'activate.php');
define('registerfile', 'register.php');


//template files
define('indexHead', 'themes/indexhead.htm');
define('indexTop', 'themes/indextop.htm');
define('loginForm', 'themes/loginform.php');
define('activationForm', 'themes/activationform.php');
define('indexMiddle', 'themes/indexmiddle.htm');
define('registerForm', 'themes/registerform.php');
define('indexFooter', 'themes/indexfooter.htm');
define('userPage', 'themes/userpage.php');

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$user = new User();
$user->dbConnect(conString, dbUser, dbPass);

0 个答案:

没有答案