不会引发PDO异常 [英] PDO exception is not being thrown

查看:82
本文介绍了不会引发PDO异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是PDO的新手,有一些使我感到困惑的地方,我尝试创建一个测试函数来查看是否会为无效查询引发异常,但不会引发任何异常.

I am new to PDO and a few things about it confuse me, I've tried creating a test function to see whether an exception will be thrown for an invalid query but nothing is thrown.

这是代码

<?php
include_once("/var/www/include/constants.php");

class DB{
    private $DBH; 

    public function DB(){
        try{
            $DBH = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASS);   
        }
        catch(PDOException $e) {  
            echo $e->getMessage(); 
        }
    }

    public function test(){
        try{
            $DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  
            $DBH->prepare('DELECT id FROM users');  
        }
        catch(PDOException $e) {  
            echo $e->getMessage();  

        }
    }

};

/* Create database connection */
$db = new DB;
$db->test();

?>

推荐答案

除了缺少对数据库句柄$this的引用之外,您还需要告诉PDO一定不要模仿准备. 下面的代码将引发如下异常:

Besides the missing references to the $this of your database handle, your need to tell PDO that it must not emulate prepares. The code below will throw a exception like this:

SQLSTATE [42000]:语法错误或访问冲突:1064您有一个 您的SQL语法错误;检查与您的手册相对应的手册 MySQL服务器版本,可在'DELECT id FROM附近使用正确的语法 用户在第1行

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELECT id FROM users' at line 1

class DB{
    private $DBH; 

    public function DB(){
        try{
            $this->DBH = new PDO("mysql:host=localhost;dbname=movies", 'root', 'jsat12');   
            $this->DBH->setAttribute(PDO::ATTR_EMULATE_PREPARES, false );
      }
        catch(PDOException $e) {  
            echo $e->getMessage(); 
        }
    }

    public function test(){
        try{
            $this->DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );  
            $this->DBH->prepare('DELECT id FROM users');  
        }
        catch(PDOException $e) {  
            echo $e->getMessage();  

        }
    }

};

/* Create database connection */
$db = new DB;
$db->test();

这篇关于不会引发PDO异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆