Hi all,
I’m working on a project and I’m using PDO to connect to MySQL to retrieve data. I’ve been testing out my script and I’ve noticed that my try/catch blocks aren’t working when trying to catch a PDO error. It works in other projects I’ve done but its not working in this one.
Here is my code:
[php]
<?php //core\database.php namespace Core; class Database { private static $dbhost = "localhost"; private static $dbname = "test"; private static $dbport = "3306"; private static $dbuser = "root"; private static $dbpass = "test"; //mysql variables public static function Connect() { try { $db = new \PDO("mysql:host=" . self::$dbhost . ";dbname=" . self::$dbname . ";port=" . self::$dbport,self::$dbuser,self::$dbpass); $db->setAttribute(\PDO::ATTR_ERRMODE,\PDO::ERRMODE_EXCEPTION); $db->exec("SET NAMES 'utf8'"); } catch (PDOException $e) { echo "Could not connect to the database."; exit; } return $db; } } [/php] [php] <?php //model\product.php namespace Model; class Product { public $db; public function __construct($db) { $this->db = $db->Connect(); } public function getProductsAll() { try { $items = $this->db->query("SELECT id, prduct_name, product_price, product_description, product_image FROM products"); $results = $items->fetchAll(\PDO::FETCH_ASSOC); return $results; } catch(PDOException $e) { echo 'MySQL Error.'; exit; } } //product listings, order insertion } [/php] As you can see, I tried making an error occur by renaming product_name to prduct_name, but when I run the code I get this error: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'prduct_name' in 'field list'' Rather than the message in the catch block. The only thing different in this project to other projects is that I'm using namespaces and I get errors unless I use backslashes to tell PHP to use the global namespace for PDO e.g. $db = new \PDO. How can I fix this? Thanks, Adam