Zeroi9 Posted April 7, 2013 Share Posted April 7, 2013 Today, I decided to stop with mysqli, and change to PDO. I'm reading this tutorial. Here's my full code: <?php class User { public $username; protected $db; protected $user; public function __construct($db) { $this->db = $db; try { $this->db; echo "Connected to the database."; } catch(PDOException $e) { echo $e->getMessage(); } } } $pdo = new PDO("mysql:host=localhost;dbname=dbdaev", "root", ""); $pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); $user = new User($pdo); The error: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [1049] Unknown database 'dbdaev'' in C:\xampp\htdocs\index.php:29 Stack trace: #0 C:\xampp\htdocs\index.php(29): PDO->__construct('mysql:host=loca...', 'root', '') #1 {main} thrown in C:\xampp\htdocs\index.php Expected result: SQLSTATE[42000] [1049] Unknown database 'dbdaev' The database is actually named dbdev, not dbdaev, but I wanted to try the try{} catch{}. Why doesn't it show the expected result? Link to comment https://forums.phpfreaks.com/topic/276662-pdo-try-catch-error-with-database-information/ Share on other sites More sharing options...
jcbones Posted April 7, 2013 Share Posted April 7, 2013 The uncaught exception is thrown on the line: $pdo = new PDO("mysql:host=localhost;dbname=dbdaev", "root", ""); Even though your try/catch block isn't ran until: $user = new User($pdo); Link to comment https://forums.phpfreaks.com/topic/276662-pdo-try-catch-error-with-database-information/#findComment-1423454 Share on other sites More sharing options...
Andy-H Posted April 7, 2013 Share Posted April 7, 2013 The Exception is being thrown from PDO::__construct so you need to wrap ... new PDO(... in the try catch block like so: try { $pdo = new PDO("mysql:host=localhost;dbname=dbdaev", "root", ""); $pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, 1); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); } catch ( PDOException $e ) { echo $e->getMessage(); exit; // no point in continuing without a connection } I also like to use the following when using PDO: $dbh->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, sprintf( 'SET NAMES \'%1$s\' COLLATE \'%2$s\';'. 'SET CHARACTER SET %1$s;', 'utf8', 'utf8_general_ci' ) ); To avoid encoding issues Link to comment https://forums.phpfreaks.com/topic/276662-pdo-try-catch-error-with-database-information/#findComment-1423456 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.