PHP Database Class

C++, C#, Java, PHP, ect...
Post Reply
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

PHP Database Class

Post by Jackolantern »

I have started my further study of PHP to advance my abilities with it, and have started with a study of PHP's OO features. Surprisingly, I found it was quite capable in this regard, and nearly on par with its strongly-typed brethren, such as C++, Java and C#. I was amazed to see interfaces, interator constructs, constructors, destructors, several options for access control, etc. My first small project using PHP's OO capabilities was to create a flexible MySQL database script to provide clean, safe MySQL database access that encapsulates the actual database resource file, which forces all interaction to occur in the class in controlled manner. For anyone interested in using it, here is the code and anyone is free to use it:

Code: Select all

<?php
/* Database connection class. This class will function to provide clean, OO access to database functionality. It will also
* provide encapsulation to prevent accidental corruption of data. The class will contain several members:
* $db: This is a data member containing the resource file for the database. It is private to ensure encapsulation.
* __construct(): This is the constructor for DBConnector. It takes 4 parameters: $host, $name, $pw, and $database, all used 
*		to create the connection.
* SelectQueryDB(): This is a function that runs a SELECT query in the database with the supplied query string and 
*		returns the results. It takes 1 parameter: queryString (a string containing the SELECT query to run). It returns 1 
*		value: $resultsArray (an associative array with the results of the SELECT query).
* InsertQueryDB(): This is a function that runs a INSERT query in the database with the supplied query string and returns
*		TRUE or FALSE depending on if it succeeds (it will also throw an exception if it does not succeed). It takes 1
*		parameter: queryString (a string containing the INSERT query to run). It returns TRUE or FALSE to show success/failue.
* UpdateQueryDB(): This is a function that runs an UPDATE query in the database with the supplied query string and returns
*		TRUE or FALSE depending on if it succeeds (it will also throw an exception if it does not succeed). It takes 1
*		parameter: queryString (a string containing the UPDATE query to run). It returns TRUE or FALSE to show success/failue.
* DeleteQueryDB(): This is a function that runs a DELETE query in the database with the supplied query string and returns
*		TRUE or FALSE depending on if it succeeds (it will also throw an exception if it does not succeed). It takes 1
*		parameter: queryString (a string containing the DELETE query to run). It returns TRUE or FALSE to show success/failue.
* CloseDB(): This is a function used to close the database connection. It does not take any parameters, and returns no values.
**********************************************************
*            	Version: 1.0.0	Date: 8/17/10          *
**********************************************************/

class dbConnector {
	private $db;
	
	function __construct($host, $name, $pw, $database) {		
		$this->db = mysqli_connect($host, $name, $pw ) or die("Could not obtain initial connection");
		if(!$this->db) {
    		throw new Exception("Could not obtain database connection", 1);
			exit;
		}
		
		if (!mysqli_select_db($this->db, $database)){
			throw new Exception("Failed to produce db connection", 2);
			exit;
		}
	}
	
	function SelectQueryDB($queryString) {			
		$selectResult=mysqli_fetch_array(mysqli_query($this->db, $queryString));
		if (!$selectResult) {
			throw new Exception("Failed database query", 3);
		} else {
			return $selectResult;
		}
	}
	
	function InsertQueryDB($queryString) {
		$insertResult=mysqli_fetch_array(mysqli_query($this->db, $queryString));
		if (!$insertResult) {
			throw new Exception("Failed database query", 4);
		} else {
			return $insertResult;
		}
	}
	
	function UpdateQueryDB($queryString) {
		$updateResult=mysqli_fetch_array(mysqli_query($this->db, $queryString));
		if (!$updateResult) {
			throw new Exception("Failed database query", 5);
		} else {
			return $updateResult;
		}
	}
	
	function DeleteQueryDB($queryString) {
		$deleteResult=mysqli_fetch_array(mysqli_query($this->db, $queryString));
		if (!$deleteResult) {
			throw new Exception("Failed database query", 6);
		} else {
			return $deleteResult;
		}
	}
	
	function CloseDB() {
		$this->db->close();
	}
}

?>
EDIT: As a note, the exception messages are all the same by design to prevent users of the application from gaining too much detail of the class' inner-workings from seeing an accidental unhandled exception. Instead I gave each database function a unique error code to help the developer track down the error responsible. If a developer would rather have it give unique error messages, that should be self-explanatory to change.

And here is an example file of its use:

Code: Select all

<?php

require('dbConnector.php');

//Make a new database connection object
$database = new dbConnector("localhost", "scriptuser", "scriptpw", "gamedatabase");

//Try using a SELECT query
$results = $database->SelectQueryDB("SELECT * FROM players WHERE name='Jackolantern'");
$database->CloseDB();

$toWrite = $results['name'];
$toWrite2 = $results['security'];

echo "Name: $toWrite -- Security: $toWrite2";

?>
Future updates may add support for "prepared statements" in MySQL for safer data access and ease of re-querying.
The indelible lord of tl;dr
Post Reply

Return to “Coding”