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();
?>
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With