skip navigation

Content:: PHP Database Connectivity Class

PHP - Database Connectivity Class

This PHP Database Connectivity Class (DBC) is an object oriented class that has been tested in PHP5 (it should work with PHP4 with minor changes to constructors). This class was created to give one centralized location for database connectivity information. That is the user name, password, etc are stored in one central file. If you'd like to use multiple user names and passwords (which you should want to do) you can easily name another configuration array instead of $arrDBC you can call it $arrDBC-select, or $arrDBC-edit.

Website security counts on multiple aspects of the code using a seperate user that is allowed to run select commands and others for administrators that allow alter, select etc commands are great to seperate. Hopefully this module will allow this.

This has fairly full error checking built into it and is fairly simple to implement (Include, instantiate, connect, query query query, close).
The structure is just like the built in naming convention with PHP and allows connectivity to MySQL and MSSQL (requires FreeTDS).

First we need to create a database and a simple table.
# mysql > create database db_test;
# mysql > create table test_table (
	col_id int unsigned not null Primary Key auto_increment,
	col1 varchar(255),
	col2 varchar(255),
	col3 varchar(255),
	col_long longtext

Next you will have to edit the dbc.conf.php file according to your server configurations. The user, pass and db must all be configured.
$arrDBC = array(
	'host' => 'localhost',
	'user' => 'username',
	'pass' => 'password',
	'db'   => 'database', // if you don't connect to a database set to null or ''
	'type' => 'mysql',
	'conn' => 0, // auto connect 0 false 1 true
	'error' => 'die', // die or string
	'wraperror' => array(
		'0' => '',
		'1' => "
\n" ) // wrap error messages with this 0 start 1 end );

The first portion of the code is quite simple.
Removing the Error INI Checks. eh the error reporting is processed before the file is loaded so its pointless.
ini_set('error_reporting', E_ALL);

The include files
if (file_exists("./inc/")) { include ("./inc/"); } else { echo 'failed to open'; exit;}
if (file_exists("./conf/dbc.conf.php")) { include ("./conf/dbc.conf.php"); } else { echo 'failed to open dbc.conf.php'; exit;}

Create the reference variable for the class
$refDBC = new dbc($arrDBC);
Write out the query and run it
$strQuery = 'insert into test_table (col1, col2, col3, col_long) values("Data 1", "Data 2", "Data 3", "Data 4")';
Read the Query
$strQuery = 'select * from test_table;';
$resResult = $refDBC->query($strQuery);
while ($arrFetch = mysql_fetch_assoc($resResult))
	echo '<pre>'; print_r($arrFetch); echo '</pre*gt;';
Close the databse connection
Download 4,846 bytes
MD5 - 2fff65472e9c17abffdd18787bc7297c *
Download 6,828 bytes
MD5 - 16df4a10a9ec34f62d2a8225785c69d4 *

Last Modified: 2012-10-21