Re-use the database connection

This commit is contained in:
kaetemi 2014-09-02 20:39:07 +02:00
parent 6acf67d03b
commit 6fed8bad5b

View file

@ -1,274 +1,267 @@
<?php <?php
/** /**
* Handles the database connections. It uses PDO to connect to the different databases. It will use the argument of the constructor to setup a connection to the database * Handles the database connections. It uses PDO to connect to the different databases. It will use the argument of the constructor to setup a connection to the database
* with the matching entry in the $cfg global variable. * with the matching entry in the $cfg global variable.
* *
* --> First create an object of dblayer --> $db = new DBLayer('short database name used in config') * --> First create an object of dblayer --> $db = new DBLayer('short database name used in config')
* *
* --> Insert --> $db->insert( $tb_name, $data ) * --> Insert --> $db->insert( $tb_name, $data )
* $tb_name = table name in which we want to insert data * $tb_name = table name in which we want to insert data
* $data = array of data that needs to be inserted in format('fieldname' => $value) where fieldname must be a field in that table. * $data = array of data that needs to be inserted in format('fieldname' => $value) where fieldname must be a field in that table.
* *
* --> select --> $db->select( $tb_name, $data, $where ) * --> select --> $db->select( $tb_name, $data, $where )
* $tb_name = table name which we want to select * $tb_name = table name which we want to select
* $data = array of data which is then required in WHERE clause in format array('fieldname'=>$value) fieldname must be a field in that table. * $data = array of data which is then required in WHERE clause in format array('fieldname'=>$value) fieldname must be a field in that table.
* $where = string in format ('fieldname=:fieldname') where :fieldname takes it's value from $data array. * $where = string in format ('fieldname=:fieldname') where :fieldname takes it's value from $data array.
* *
* --> update --> $db->update( $tb_name, $data, $where ) * --> update --> $db->update( $tb_name, $data, $where )
* $tb_name = table name which we want to update * $tb_name = table name which we want to update
* $data = array of data which contains the filelds that need to be updated with their values in the format('fieldname' => $value,...) where fieldname must be a field in that table. * $data = array of data which contains the filelds that need to be updated with their values in the format('fieldname' => $value,...) where fieldname must be a field in that table.
* $where = string contains the filename with a value at that field in the format ('fieldname = $value') where fieldname must be a field in that table and $value is value respect to that field. * $where = string contains the filename with a value at that field in the format ('fieldname = $value') where fieldname must be a field in that table and $value is value respect to that field.
* *
* --> delete --> $db->delete( $tb_name, $data, $where ) * --> delete --> $db->delete( $tb_name, $data, $where )
* $tb_name = table name where we want to delete. * $tb_name = table name where we want to delete.
* $data = array of data which is then required in WHERE clause in format array('fieldname'=> $value) where fieldname must be a field in that table. * $data = array of data which is then required in WHERE clause in format array('fieldname'=> $value) where fieldname must be a field in that table.
* $where = string in format ('fieldname=:fieldname') where :fieldname takes it's value from $data array. * $where = string in format ('fieldname=:fieldname') where :fieldname takes it's value from $data array.
* *
* *
* @author Daan Janssens, mentored by Matthew Lagoe * @author Daan Janssens, mentored by Matthew Lagoe
* *
*/ */
$PDOCache = array();
class DBLayer { class DBLayer {
private $PDO; private $PDO;
/** /**
* The PDO object, instantiated by the constructor * The PDO object, instantiated by the constructor
*/ */
/** /**
* The constructor. * The constructor.
* Instantiates the PDO object attribute by connecting to the arguments matching database(the db info is stored in the $cfg global var) * Instantiates the PDO object attribute by connecting to the arguments matching database(the db info is stored in the $cfg global var)
* *
* @param $db String, the name of the databases entry in the $cfg global var. * @param $db String, the name of the databases entry in the $cfg global var.
* @param $dbn String, the name of the databases entry in the $cfg global var if $db referenced to an action(install etc). * @param $dbn String, the name of the databases entry in the $cfg global var if $db referenced to an action(install etc).
*/ */
function __construct( $db, $dbn = null ) function __construct($db, $dbn = null)
{ {
if ( $db != "install" ) { global $PDOCache;
if (isset($PDOCache[$db])) {
global $cfg; $this->PDO = $PDOCache[$db];
$dsn = "mysql:"; } else {
$dsn .= "host=" . $cfg['db'][$db]['host'] . ";"; global $cfg;
$dsn .= "dbname=" . $cfg['db'][$db]['name'] . ";"; $dsn = "mysql:";
$dsn .= "port=" . $cfg['db'][$db]['port'] . ";"; $dsn .= "host=" . $cfg['db'][$db]['host'] . ";";
$dsn .= "dbname=" . $cfg['db'][$db]['name'] . ";";
$opt = array( $dsn .= "port=" . $cfg['db'][$db]['port'] . ";";
PDO :: ATTR_ERRMODE => PDO :: ERRMODE_EXCEPTION,
PDO :: ATTR_DEFAULT_FETCH_MODE => PDO :: FETCH_ASSOC $opt = array(
); PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
$this -> PDO = new PDO( $dsn, $cfg['db'][$db]['user'], $cfg['db'][$db]['pass'], $opt ); PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
} else { );
global $cfg; $this->PDO = new PDO($dsn, $cfg['db'][$db]['user'], $cfg['db'][$db]['pass'], $opt);
$dsn = "mysql:"; $PDOCache[$db] = $this->PDO;
$dsn .= "host=" . $cfg['db'][$dbn]['host'] . ";"; }
$dsn .= "port=" . $cfg['db'][$dbn]['port'] . ";"; }
$opt = array( /**
PDO :: ATTR_ERRMODE => PDO :: ERRMODE_EXCEPTION, * Execute a query that doesn't have any parameters.
PDO :: ATTR_DEFAULT_FETCH_MODE => PDO :: FETCH_ASSOC *
); * @param $query the mysql query.
$this -> PDO = new PDO( $dsn, $_POST['Username'], $_POST['Password'], $opt ); * @return returns a PDOStatement object.
} */
public function executeWithoutParams($query) {
} $statement = $this->PDO->prepare($query);
$statement->execute();
/** return $statement;
* Execute a query that doesn't have any parameters. }
*
* @param $query the mysql query. /**
* @return returns a PDOStatement object. * Execute a query that has parameters.
*/ *
public function executeWithoutParams( $query ) { * @param $query the mysql query.
$statement = $this -> PDO -> prepare( $query ); * @param $params the parameters that are being used by the query.
$statement -> execute(); * @return returns a PDOStatement object.
return $statement; */
} public function execute( $query, $params ) {
$statement = $this -> PDO -> prepare( $query );
/** $statement -> execute( $params );
* Execute a query that has parameters. return $statement;
* }
* @param $query the mysql query.
* @param $params the parameters that are being used by the query. /**
* @return returns a PDOStatement object. * Insert function which returns id of the inserting field.
*/ *
public function execute( $query, $params ) { * @param $tb_name table name where we want to insert data.
$statement = $this -> PDO -> prepare( $query ); * @param $data the parameters that are being inserted into table.
$statement -> execute( $params ); * @return returns the id of the last inserted element.
return $statement; */
} public function executeReturnId( $tb_name, $data ) {
$field_values = ':' . implode( ',:', array_keys( $data ) );
/** $field_options = implode( ',', array_keys( $data ) );
* Insert function which returns id of the inserting field. try {
* $sth = $this -> PDO -> prepare( "INSERT INTO $tb_name ($field_options) VALUE ($field_values)" );
* @param $tb_name table name where we want to insert data. foreach ( $data as $key => $value )
* @param $data the parameters that are being inserted into table. {
* @return returns the id of the last inserted element. $sth -> bindValue( ":$key", $value );
*/ }
public function executeReturnId( $tb_name, $data ) { $this -> PDO -> beginTransaction();
$field_values = ':' . implode( ',:', array_keys( $data ) ); $sth -> execute();
$field_options = implode( ',', array_keys( $data ) ); $lastId = $this -> PDO -> lastInsertId();
try { $this -> PDO -> commit();
$sth = $this -> PDO -> prepare( "INSERT INTO $tb_name ($field_options) VALUE ($field_values)" ); }
foreach ( $data as $key => $value ) catch ( Exception $e )
{ {
$sth -> bindValue( ":$key", $value ); // for rolling back the changes during transaction
} $this -> PDO -> rollBack();
$this -> PDO -> beginTransaction(); throw new Exception( "error in inseting" );
$sth -> execute(); }
$lastId = $this -> PDO -> lastInsertId(); return $lastId;
$this -> PDO -> commit(); }
}
catch ( Exception $e ) /**
{ * Select function using prepared statement.
// for rolling back the changes during transaction * For selecting particular fields.
$this -> PDO -> rollBack(); *
throw new Exception( "error in inseting" ); * @param string $param field to select, can be multiple fields.
} * @param string $tb_name Table Name to Select.
return $lastId; * @param array $data array of data to be used in WHERE clause in format('fieldname'=>$value). 'fieldname' must be a field in that table.
} * @param string $where where to select.
* @return statement object.
/** */
* Select function using prepared statement. public function selectWithParameter( $param, $tb_name, $data, $where )
* For selecting particular fields. {
* try {
* @param string $param field to select, can be multiple fields. $sth = $this -> PDO -> prepare( "SELECT $param FROM $tb_name WHERE $where" );
* @param string $tb_name Table Name to Select. $this -> PDO -> beginTransaction();
* @param array $data array of data to be used in WHERE clause in format('fieldname'=>$value). 'fieldname' must be a field in that table. $sth -> execute( $data );
* @param string $where where to select. $this -> PDO -> commit();
* @return statement object. }
*/ catch ( Exception $e ) {
public function selectWithParameter( $param, $tb_name, $data, $where ) $this -> PDO -> rollBack();
{ throw new Exception( "error selection" );
try { return false;
$sth = $this -> PDO -> prepare( "SELECT $param FROM $tb_name WHERE $where" ); }
$this -> PDO -> beginTransaction(); return $sth;
$sth -> execute( $data ); }
$this -> PDO -> commit();
} /**
catch( Exception $e ) * Select function using prepared statement.
{ * For selecting all fields in a table.
$this -> PDO -> rollBack(); *
throw new Exception( "error selection" ); * @param string $tb_name Table Name to Select.
return false; * @param array $data array of data to be used with WHERE part in format('fieldname'=>$value,...). 'fieldname' must be a field in that table.
} * @param string $where where to select in format('fieldname=:fieldname' AND ...).
return $sth; * @return statement object.
} */
public function select( $tb_name, $data , $where )
/** {
* Select function using prepared statement. try {
* For selecting all fields in a table. $sth = $this -> PDO -> prepare( "SELECT * FROM $tb_name WHERE $where" );
* $this -> PDO -> beginTransaction();
* @param string $tb_name Table Name to Select. $sth -> execute( $data );
* @param array $data array of data to be used with WHERE part in format('fieldname'=>$value,...). 'fieldname' must be a field in that table. $this -> PDO -> commit();
* @param string $where where to select in format('fieldname=:fieldname' AND ...). }
* @return statement object. catch( Exception $e )
*/ {
public function select( $tb_name, $data , $where ) $this -> PDO -> rollBack();
{ throw new Exception( "error selection" );
try { return false;
$sth = $this -> PDO -> prepare( "SELECT * FROM $tb_name WHERE $where" ); }
$this -> PDO -> beginTransaction(); return $sth;
$sth -> execute( $data ); }
$this -> PDO -> commit();
} /**
catch( Exception $e ) * Update function with prepared statement.
{ *
$this -> PDO -> rollBack(); * @param string $tb_name name of the table on which operation to be performed.
throw new Exception( "error selection" ); * @param array $data array of data in format('fieldname' => $value,...).Here, only those fields must be stored which needs to be updated.
return false; * @param string $where where part in format ('fieldname'= $value AND ...). 'fieldname' must be a field in that table.
} * @throws Exception error in updating.
return $sth; */
} public function update( $tb_name, $data, $where )
{
/** $field_option_values = null;
* Update function with prepared statement. foreach ( $data as $key => $value )
* {
* @param string $tb_name name of the table on which operation to be performed. $field_option_values .= ",$key" . '=:' . $key;
* @param array $data array of data in format('fieldname' => $value,...).Here, only those fields must be stored which needs to be updated. }
* @param string $where where part in format ('fieldname'= $value AND ...). 'fieldname' must be a field in that table. $field_option_values = ltrim( $field_option_values, ',' );
* @throws Exception error in updating. try {
*/ $sth = $this -> PDO -> prepare( "UPDATE $tb_name SET $field_option_values WHERE $where " );
public function update( $tb_name, $data, $where )
{ foreach ( $data as $key => $value )
$field_option_values = null; {
foreach ( $data as $key => $value ) $sth -> bindValue( ":$key", $value );
{ }
$field_option_values .= ",$key" . '=:' . $key; $this -> PDO -> beginTransaction();
} $sth -> execute();
$field_option_values = ltrim( $field_option_values, ',' ); $this -> PDO -> commit();
try { }
$sth = $this -> PDO -> prepare( "UPDATE $tb_name SET $field_option_values WHERE $where " ); catch ( Exception $e )
{
foreach ( $data as $key => $value ) $this -> PDO -> rollBack();
{ throw new Exception( 'error in updating' );
$sth -> bindValue( ":$key", $value ); return false;
} }
$this -> PDO -> beginTransaction(); return true;
$sth -> execute(); }
$this -> PDO -> commit();
} /**
catch ( Exception $e ) * insert function using prepared statements.
{ *
$this -> PDO -> rollBack(); * @param string $tb_name Name of the table on which operation to be performed.
throw new Exception( 'error in updating' ); * @param array $data array of data to insert in format('fieldname' => $value,....). 'fieldname' must be a field in that table.
return false; * @throws error in inserting.
} */
return true; public function insert( $tb_name, $data )
} {
$field_values = ':' . implode( ',:', array_keys( $data ) );
/** $field_options = implode( ',', array_keys( $data ) );
* insert function using prepared statements. try {
* $sth = $this -> PDO -> prepare( "INSERT INTO $tb_name ($field_options) VALUE ($field_values)" );
* @param string $tb_name Name of the table on which operation to be performed. foreach ( $data as $key => $value )
* @param array $data array of data to insert in format('fieldname' => $value,....). 'fieldname' must be a field in that table. {
* @throws error in inserting.
*/ $sth -> bindValue( ":$key", $value );
public function insert( $tb_name, $data ) }
{ $this -> PDO -> beginTransaction();
$field_values = ':' . implode( ',:', array_keys( $data ) ); // execution
$field_options = implode( ',', array_keys( $data ) ); $sth -> execute();
try { $this -> PDO -> commit();
$sth = $this -> PDO -> prepare( "INSERT INTO $tb_name ($field_options) VALUE ($field_values)" );
foreach ( $data as $key => $value ) }
{ catch ( Exception $e )
{
$sth -> bindValue( ":$key", $value ); // for rolling back the changes during transaction
} $this -> PDO -> rollBack();
$this -> PDO -> beginTransaction(); throw new Exception( "error in inserting" );
// execution }
$sth -> execute(); }
$this -> PDO -> commit();
/**
} * Delete database entery using prepared statement.
catch ( Exception $e ) *
{ * @param string $tb_name table name on which operations to be performed.
// for rolling back the changes during transaction * @param $data array with values in the format('fieldname'=> $value,...). 'fieldname' must be a field in that table.
$this -> PDO -> rollBack(); * @param string $where condition based on $data array in the format('fieldname=:fieldname' AND ...).
throw new Exception( "error in inserting" ); * @throws error in deleting.
} */
} public function delete( $tb_name, $data, $where )
{
/** try {
* Delete database entery using prepared statement. $sth = $this -> PDO -> prepare( "DELETE FROM $tb_name WHERE $where" );
* $this -> PDO -> beginTransaction();
* @param string $tb_name table name on which operations to be performed. $sth -> execute( $data );
* @param $data array with values in the format('fieldname'=> $value,...). 'fieldname' must be a field in that table. $this -> PDO -> commit();
* @param string $where condition based on $data array in the format('fieldname=:fieldname' AND ...). }
* @throws error in deleting. catch ( Exception $e )
*/ {
public function delete( $tb_name, $data, $where ) $this -> PDO -> rollBack();
{ throw new Exception( "error in deleting" );
try { }
$sth = $this -> PDO -> prepare( "DELETE FROM $tb_name WHERE $where" );
$this -> PDO -> beginTransaction(); }
$sth -> execute( $data ); }
$this -> PDO -> commit();
}
catch ( Exception $e )
{
$this -> PDO -> rollBack();
throw new Exception( "error in deleting" );
}
}
}