Jump to content

PDO try{} catch{} error with database information.


Zeroi9

Recommended Posts

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?

 

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.