Jump to content

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


Go to solution Solved by jcbones,

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.