PDO utilising OOP

Building on the previous examples of moving functions into external files, we can now develop an OO class that will perform the same functions.

 

The error_handling.php and pdoBinder.php files can be placed into a single pdoClass.php file, and encapsulated within a class as follows:

<?php

	class pdoClass{

		public function arrayBinder(&$pdoStatement, &$array) {

			foreach($array as $key=>$value){
				$pdoStatement->bindValue(':'.$key,$value);
			}
		}

		public 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 only difference here is that the previous functions have now been prefixed with the public visibility keyword.

 

The pdoClass.php can now be included within the main file as per line 4, and an object instantiated upon it as per line 8. The $myObject object is then used with the access operator -> on lines 16 and 22 to perform the same functionality as previously but we are now using an object oriented approach:

<?php
	ini_set('display_errors', '0');
	include_once('connect.php');
	include_once('pdoClass.php');
	$team = 'Honda';
	$status = 'Factory';

	$myObject = new pdoClass(); //instantiates an object

	$sqlQuery = "SELECT * from riders where team = :team AND status = :status";

	$statement = $dbh->prepare($sqlQuery);

	$myArr = array('team'=>$team, 'status'=>$status);

	$myObject->arrayBinder($statement, $myArr);

	try{
		$statement->execute();
	}
	catch(PDOException $error){
		echo $myObject->errorHandling($error);
	}

	while($row = $statement->fetch(PDO::FETCH_ASSOC)) {
		echo $row['name'] . " rides a " . $row['team'] . " " . $row['status'] . " MotoGP bike!<br>";
	}
?>

Save & refresh browser:

Connected to the motogp database
Dani Pedrosa rides a Honda Factory MotoGP bike!
Marc Marquez rides a Honda Factory MotoGP bike!
Stefan Bradl rides a Honda Factory MotoGP bike!
Alvaro Bautista rides a Honda Factory MotoGP bike!

Leave a Reply