无法在PHP中使用PDO获取错误信息

时间:2016-01-20 01:30:29

标签: php mysql pdo

我正在学习PDO,并且正在尝试在我当前的项目中实现它。当我使用mysqli时,我可以使用mysqli_error($connection)获取有关任何错误的详细信息。我搜索了PDO的可比性,发现this帖子,并决定在我的代码中实现它。但是,即使我知道sql语句中存在明显错误,我也无法收到任何错误消息。

相关代码:

class Database {

public $connection;

function __construct() {
    $this->open_database_connection();
}

public function open_database_connection() {


    try {

        $this->connection = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);

        $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->connection->setAttribute( PDO::ATTR_EMULATE_PREPARES, false);


    } catch(PDOException $e) {
        echo $e->getMessage();  
        die('Could not connect');
    }

} // end of open_database_connection method




public function query($sql, $params = []) {

    try {

        $query = $this->connection->prepare($sql);

    } catch (Exception $e) {
        var_dump('mysql error: ' . $e->getMessage());
    }


    foreach($params as $key => $value) {
        if ($key === ':limit') {
            $query->bindValue($key, $value, PDO::PARAM_INT);

        } else {
            $query -> bindValue($key, $value);
        }
    }

    try {

        $query->execute();

    } catch(Exception $e) {
        echo 'Exception -> ';
        var_dump($e->getMessage());
    }


    /*
    DID NOT WORK:
    if (!$query->execute()) {
            print_r($query->errorinfo());

    }*/

      $result = $query->fetchAll(PDO::FETCH_ASSOC);

        $this->confirm_query($result); 
        return $result; 

}  // end of query method



  function confirm_query($query) {

    if (!$query) {
        die('mysql error: ');
}

}

当我运行代码时,我确实得到了" mysql错误",但我没有得到任何有关它的细节。我做错了什么?

更新:根据要求,我在下面提供了其他详细信息。

我要做的是验证用户的登录详细信息。为此,一旦用户输入他的凭据,此代码就会运行:

if (isset($_POST['submit'])) {

    $username = trim($_POST['username']);
    $password = trim($_POST['password']);

    //check the database for the user

    $user_found = User::verify_user($username, $password);

User类的相关代码:

    public static function verify_user($username, $password) {

        global $db;

        $username = $db->escape_string($username);
        $password = $db->escape_string($password);

        $values = [ ":username" => $username,
                    ":password" => $password,
                    ":limit" => 1
                  ];


        $result_array = self::find_this_query("SELECT * FROM users WHERE username=:username AND password=:password LIMIT :limit", true, $values);


        return !empty($result_array)? array_shift($result_array) : false;

    }




    public static function find_this_query($sql, $prepared = false, $params = []) {

        global $db;

        $the_object_array = array();
        $result = $db->query($sql, $params);

        $arr_length = count($result);

        for ($i = 0; $i < $arr_length; $i++) {

            $the_object_array[] = self::instantiation($result[$i]);
        }

        return $the_object_array;

    }


    public static function instantiation($the_record) {

        $the_object =new self; //we need new self because $the_record corresponds to one user!



        foreach($the_record as $the_attribute => $value) {

            if ($the_object->has_the_attribute($the_attribute)) {
                $the_object->$the_attribute = $value;
            }
        }


        return $the_object;

    }

    public function has_the_attribute($attribute) {

        $object_properties = get_object_vars($this);

        return array_key_exists($attribute, $object_properties);
    }

1 个答案:

答案 0 :(得分:0)

您必须使用PDO :: errorInfo():

(env_py34)root@8a7953c24d4f:/home# python
Python 3.4.3 (default, Oct 14 2015, 20:28:29) 
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tkinter as tk
Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 39, in <module>
    import _tkinter
ImportError: No module named '_tkinter'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/tkinter/__init__.py", line 41, in <module>
    raise ImportError(str(msg) + ', please install the python3-tk package')
ImportError: No module named '_tkinter', please install the python3-tk package
>>> 

PDO :: errorInfo返回一个数组:

  

元素0:SQLSTATE错误代码(ANSI SQL标准中定义的五个字符的字母数字标识符);

     

元素1:特定于驱动程序的错误代码;

     

元素2:特定于驱动程序的错误消息。