Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDO exception is not being thrown

Tags:

php

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.

here is the code

<?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();

?>
like image 516
mk_89 Avatar asked Oct 13 '12 11:10

mk_89


1 Answers

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]: 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();
like image 175
JvdBerg Avatar answered Sep 19 '22 02:09

JvdBerg