Handling Errors

Let's try handling errors. To handle errors from PHP PDO, we use a try..catch block.

This makes it simple to catch errors from the database.

<?php
// make a connection to the MySQL server
$db = new PDO("mysql:host=localhost;dbname=employees;", "[username]", "[password]");

// turn on PDO options
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

$results = [];

try {

	// prepare a query
	$prep = $db->prepare("select lastName, firstName, state from names n left join addresses a on n.id=a.nameId order by state");

	// execute the query
	$prep->execute();
	
	// fetch the results and put them into a variable
	$results = $prep->fetchAll();

} catch(PDOException $e) {
	
	echo "There was a database error:<br>";
	echo $e->getMessage() . "<br>";
	exit;
	
}

// echo the results to the browser
foreach ($results as $res) {
	echo "<div>{$res["lastName"]}, {$res["firstName"]} in {$res["state"]}</div>";
}

In this code, everything will work just fine and no errors will occur. Let's create a bad query on purpose. Replace the line:

select lastName, firstName, state from names n left join addresses a on n.id=a.nameId order by state

with:

select lastName, firstName, state from names n left join addresses a on n.id=a.nameId order by stat

We've only removed one character at the very end of the query, an e. This is a common mistyping.

You should get the following output after reloading the page:

There was a database error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'stat' in 'order clause'

In the previous example, we added quite a few changes. We'll add one more. What happens when we can't connect to the database? We need to handle that situation as well.

<?php
$db = null;

try {
	
	// make a connection to the MySQL server
	$db = new PDO("mysql:host=localhost;dbname=employees;", "[username]", "[password]");

	// turn on PDO options
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

} catch(PDOException $e) {
	echo "Couldn't connect to MySQL server:<br>";
	echo $e->getMessage() . "<br>";
	exit;
}

$results = [];

try {

	// prepare a query
	$prep = $db->prepare("select lastName, firstName, state from names n left join addresses a on n.id=a.nameId order by state");

	// execute the query
	$prep->execute();
	
	// fetch the results and put them into a variable
	$results = $prep->fetchAll();

} catch(PDOException $e) {
	
	echo "There was a database error:<br>";
	echo $e->getMessage() . "<br>";
	exit;
	
}

// echo the results to the browser
foreach ($results as $res) {
	echo "<div>{$res["lastName"]}, {$res["firstName"]} in {$res["state"]}</div>";
}

If you disable your MySQL server so that you can't connect to it, you'll get the following output after running this code:

Couldn't connect to MySQL server:
SQLSTATE[HY000] [2002] No such file or directory