在类中获取未知错误

时间:2015-07-22 21:12:23

标签: php web pdo error-handling

我试图为我的网站制作一个基于令牌的系统,并且我正在使用php制作类。当我在check函数内运行PDO查询时,页面停止工作。

<?php 

date_default_timezone_set("Europe/Copenhagen");
include_once ("../connect.php");

class userToken {

    public $token;

    public $tokenid;
    public $userId;
    public $expire;

    function __construct($t) {
        $this->tokken = $t;
        $this->check();

    }

    public function check() {
        try {

            $checkToken = $DBH->prepare("
                SELECT *
                FROM token
                WHERE token = :token
                LIMIT 1
            ");

            $checkToken->execute(array(':token' => "186382asd"));

        } catch(PDOException $e) {

            echo $e->getMessage();
            echo '[{"error":true"}]';
            exit();

        }
        return "done";

    }

}

$test = new userToken("186382asd");

echo $test->token;
?>

1 个答案:

答案 0 :(得分:1)

您的代码中几乎所有内容都不起作用;

    您的$dbh方法中不存在
  • check
  • 构造函数中的错字tokken
  • 您没有设置$this->token
  • 您注入的令牌未传递给该方法,因此您的查询不是动态的

我重新格式化了代码;

// -- connect.php
error_reporting(E_ALL);
$dbh = new PDO($dsn, $user, $pass);
// -- yourfile.php
$token = '186382asd';
$object = new UserToken($dbh);
var_dump($object->check($token)); // result or false

class UserToken {

    public function __construct($dbh) {
        $this->dbh = $dbh;
    }

    public function check($token) {
        try {
            $stmt = $this->dbh->prepare("
                SELECT *
                FROM token
                WHERE token = :token
                LIMIT 1
            ");
            return $stmt->execute(array(':token' => $token));
        } catch (PDOException $e) {
            echo $e->getMessage();
            echo '[{"error":true"}]';
        }
    }

}