PDO Exceptions

A PDOException will be thrown if there are any connection errors. These can be caught in a try/catch block.

 

The PDO::setAttribute() method is used to set the error reporting level as follows:

  • PDO::ATTR_ERRMODE: Error reporting.
    • PDO::ERRMODE_SILENT: Just set error codes.
    • PDO::ERRMODE_WARNING: Raise E_WARNING.
    • PDO::ERRMODE_EXCEPTION: Throw exceptions.

Syntax:

$object->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

 

Exception methods can now be used:

getCode()

getMessage()

getTrace()

getFile()

getLine()

returns error code

returns the exception message

returns the exception stack trace as an array

returns the name of the file the exception was created

returns the line number where the exception was created

 

For this example, to show the connection error being caught, I have changed the username to potato:

<?php
	$host = 'localhost';
	$dbname = 'motogp';
	$dsn = "mysql:host=$host;dbname=$dbname";
	$username = "potato";
	$password = "secret";
	try {
		$dbh = new PDO($dsn, $username, $password); //database handle
		$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //set error reporting level

		echo "Connected to the $dbname database<br>";

		$sqlQuery = 'SELECT * from riders';//select everything from the riders table

		foreach($dbh->query($sqlQuery) as $row) {
			echo $row['rider_name'] . " rides for " . $row['rider_team'] . "<br>";
		}
		$dbh = null; //close connection
	}
	catch (PDOException $error) { //catch PDOException
		echo "Error!: " . $error->getMessage() . "<br>";
		file_put_contents( './dbErrors.txt', $error->getMessage(), FILE_APPEND );
		die("Can't Connect!");
	}
?>

Save & refresh browser:

Error!: SQLSTATE[28000] [1045] Access denied for user 'potato'@'localhost' (using password: YES)

Leave a Reply