Organising Files

Whilst not strictly a PDO concept, I am showing the use of placing some of the code into external files that are then included.


This will keep the examples slightly shorter and show modularity.


First the connection to the database:

	$db_host = 'localhost';
	$db_name = 'motogp';
	$dsn = "mysql:host=$db_host;dbname=$db_name";
	$db_username = "testing";
	$db_password = "secret";
	$dbh = new PDO($dsn, $db_username, $db_password);
		throw PDOException;
	} else {
		echo "Connected to the $db_name database<br>";

Save & refresh browser:

Connected to the motogp database


Changing any of the connection variables throws an exception :

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2005] Unknown MySQL server host 'xxxxxxx' (25)' in /path/user/public_html/pdo/connect.php:7 Stack trace: #0 /path/user/public_html/pdo/connect.php(7): PDO->__construct('mysql:host=xxxx...', 'testing', 'secret') #1 {main} thrown in /path/user/public_html/pdo/connect.php on line 7



Now the error handling:

	function errorHandling(Exception $error) {
		echo "Error!<br/>";

		$diag = $error->getTrace();
		if($diag[0]['class'] != ""){
			$diagClass = $diag[0]['class'];
		$func = $diag[0]['function'];
		$file = $diag[0]['file'];
		$line = $diag[0]['line'];
		$errorMessage = $error->getMessage() . "<br>" .
		"Class & Method: " . $diagClass . " & " . $func . "<br>" .
		"File: " . $file . "<br>" .
		"Line: " . $line . "<br>";

		echo $errorMessage;

		file_put_contents( './dbErrors.txt', $errorMessage, FILE_APPEND );


The above files can now be included where required and provide neater more readable code:

//turn errors off (since we're doing it ourselves in error_handling.php
	ini_set('display_errors', '0');

	//connect to the database
	//make sure to use the customised error handling

	//now do a query
		$sqlQuery = 'SELECT * from riders';//select everything from the riders table

		foreach($dbh->query($sqlQuery) as $row) {
			echo $row['name'] . " rides for " . $row['team'] . "<br>";
	catch (PDOException $error) { //catch PDOException
		echo "Error!: " . $error->getMessage() . "<br/>";
		file_put_contents( './dbErrors.txt', $error->getMessage() . "\n", FILE_APPEND );

Save & refresh browser:

Connected to the motogp database
Dani Pedrosa rides for Honda
Jorge Lorenzo rides for Yamaha
Marc Marquez rides for Honda
Cal Crutchlow rides for Yamaha
Valentino Rossi rides for Yamaha
Andrea Dovizioso rides for Ducati
Stefan Bradl rides for Honda
Nicky Hayden rides for Ducati
Alvaro Bautista rides for Honda
Aleix Espargaro rides for ART

Leave a Reply