注册用户抛出异常

时间:2015-03-17 07:47:23

标签: php oop

我正在关注PHPAcademy的OOP登录/注册教程。我目前正处于该系列的第15个视频中。 (https://www.youtube.com/watch?v=G3hkHIoDi6M&list=PLfdtiltiRHWF5Rhuk7k4UAU1_yLAZzhWc&index=15

当我注册用户时,它会抛出异常。一切似乎都很好。我检查了YouTube评论和其他网站,但没有任何方法可以解决此问题。

db.php中

<?php
class DB{
private static $_instance = null;
private $_pdo, 
        $_query, 
        $_error = false,
        $_results,
        $_count = 0;

private function __construct()
{
    try
    {
    $this->_pdo = new PDO('mysql:host='.Config::get('mysql/host').';'.
                            'dbname='.Config::get('mysql/db'),
                            Config::get('mysql/username'),
                            Config::get('mysql/password')
        );
    }
    catch(PDOException $e)
    {
        die($e->getMessage());
    }
}

public static function getInstance()
{
    if(!isset(self::$_instance))
    {
        self::$_instance = new DB();
    }
    return self::$_instance;
}

public function query($sql, $params = array())
{
    $this->error = false;
    if($this->_query = $this->_pdo->prepare($sql))
    {   
        $x = 1;
        if(count($params))
        {
            foreach ($params as $param) 
            {
                $this->_query->bindvalue($x, $param);
                $x++;
            }
        }

        if($this->_query->execute())
        {
            $this->_requests    = $this->_query->fetchAll(PDO::FETCH_OBJ);
            $this->_count       = $this->_query->rowCount();
        }
        else
        {
            $this->_error = true;
        }
    }

    return $this;
  }

  public function action($action, $table, $where = array())
  {
    if(count($where) === 3)
    {
        $operators  = array('=', '>', '<', '>=', '<=');

        $field      = $where[0];
        $operator   = $where[1];
        $value      = $where[2];

        if(in_array($operator, $operators))
        {
            $sql = "{$action} * FROM {$table} WHERE {$field} {$operator} ?";
            if(!$this->query($sql, array($value))->error())
            {
                return $this;
            }
        }
    }
    return false;
}

public function get($table, $where)
{
    return $this->action('SELECT', $table, $where);
}

public function delete($table, $where)
{
    return $this->action('DELETE', $table, $where);
}

public function insert($table, $fields = array())
{
    if(count($fields))
    {
        $keys   = array_keys($fields);
        $values = '';
        $x      = 1;

        foreach ($fields as $field) {
            $values .= '?';
            if($x < count($fields))
            {
                $values .= ', ';
            }
            $x++;
        }

        // die($values);

        $sql = "INSERT INTO {$table} (`".implode('`, `', $keys)."`) VALUES ({$values})";

        if(!$this->query($sql, $fields)->error())
        {
            return true;
        }
    }
    return false;
}

public function update($table, $id, $fields)
{
    $set    = '';
    $x      = 1;

    foreach ($fields as $name => $value) {
        $set .= "{$name} = ?";
        if($x < count($fields))
        {
            $set .= ', ';
        }
        $x++;
    }

    $sql = "UPDATE {$table} SET {$set} WHERE uid = {$id}";

    if(!$this->query($sql, $fields)->error())
    {
        return true;
    }
    return false;
}

public function results()
{
    return $this->_results;
}

public function first()
{
    return $this->results()[0];
}

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

public function count()
{
    return $this->_count;
}
}

user.php的

<?php

class User{
private $_db;

public function __construct($user = null)
{
    $this->_db = DB::getInstance();
}

public function create($fields = array())
{
    if(!$this->_db->insert('users', $fields))
    {
        throw new Exception('Problem creating user account');
    }
}
}

Hash.php

<?php

class Hash {
public static function make($string, $salt = '')
{
    return hash('sha256', $string . $salt);
}

public static function salt($length)
{
    return utf8_encode(mcrypt_create_iv($length));
}

public static function unique()
{
    return self::make(uniqid());
}
}

Register.php

<?php
require 'core/init.php';

if(Input::exists()){
    if(Token::check(Input::get('token')) )
    {
        $validate = new Validation();
        $validation = $validate->check($_POST, array(
            'username' => array(
                'required' => true,
                'min' => 2,
                'max' => 20,
                'unique' => 'users'
            ),

            'password' => array(
                'required' => true,
                'min' => 6
            ),

            'password_again' => array(
                'required' => true,
                'matches' => 'password'
            ),

            'name' => array(
                'required' => true,
                'min' => 2,
                'max' => 50
            )
        ));

        if($validate->passed()){
            $user = new User();

            $salt = Hash::salt(32);

            try{
                $user->create(array(
                    'username'  => Input::get('username'),
                    'password'  => Hash::make(Input::get('password'), $salt),
                    'salt'      => $salt,
                    'name'      => Input::get('name'),
                    'joined'    => date('Y-m-d H:i:s'),
                    'group'     => 1
                    )
                );
            } catch(Exception $e) {
                die($e->getMessage());
            }
        }
        else{
            foreach ($validate->errors() as $error) {
                echo $error . '<br />';
            }
        }
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Register</title>
</head>
<body>
    <form action="" method="POST">
        <div class="field">
            <label for="username">Username:</label>
            <input type="text" name="username" id="username" value="<?php echo escape(Input::get('username')); ?>" autocomplete="off">
        </div>

        <div class="field">
        <label for="password">Password:</label>
            <input type="password" name="password" id="password">
        </div>

        <div class="field">
        <label for="password_again">Repeat Password:</label>
            <input type="password" name="password_again" id="password_again">
        </div>

        <div class="field">
        <label for="name">Name:</label>
            <input type="text" name="name" id="name" value="<?php echo escape(Input::get('name')); ?>">
        </div>

        <input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
        <input type="submit" value="Register me">
    </form>
</body>
</html>

Input.php

<?php
class Input {
    public static function exists($type = 'POST')
    {
        switch ($type) {
            case 'POST':
                return (!empty($_POST)) ? true : false;
                break;

            case 'get':
                return (!empty($_GET)) ? true : false;
                break;

            default:
                return false;
                break;
        }
    }

    public static function get($item)
    {
        if(isset($_POST[$item]))
        {
            return $_POST[$item];
        }
        elseif (isset($_GET[$item])) {
            return $_POST[$item];
        }
        return '';
    }
}

当我错误地填写表单时,它会显示验证错误。当我正确填写时,它会显示User.php文件中指定的“创建用户帐户时出现问题”。

1 个答案:

答案 0 :(得分:0)

query()方法进行以下临时更改,以查看问题所在。它看起来像一个查询错误:

    if($this->_query->execute())
    {
        $this->_requests    = $this->_query->fetchAll(PDO::FETCH_OBJ);
        $this->_count       = $this->_query->rowCount();
    }
    else
    {
        $this->_error = true;
        print_r($this->_query->errorInfo()); // New code line 1
        exit();                              // New code line 2
    }

然后告诉我们它的内容。