Yeah, good idea, but it does look a bit messy though.
Maybe try using a class instead? Here's a snippet from a SQL wrapper class I wrote. It supports MySQL and PostgreSQL and can easly be modified to support other databases:
/* Wrapper class for handling databases.
*
* Currently supports MySQL and PostgreSQL databases.
* Can be expanded to support many other databases as per PHP documentation.
*
*/
class SQL{
var $sDatabase, // String containing database provider name. Eg. MySQL or PostgreSQL
$dbi, // Contains the current connection to the database.
$bDebug, // Debug flag, which will print queries to the database to the screen.
$aResults, // An array of result identifiers. (result identifiers are returned from successfull queries.
// User can specify which result identifer they wish to use on most functions.
$sQuery; // String containing current database query.
// Constructor
// $sDatabase Set name of database provider being used.
function SQL($sDatabase){
$this->sDatabase = strtolower($sDatabase);
$this->bDebug = false;
}
// Will turn on or off debuggind depending on current state.
function toggleDebug(){
if($this->bDebug == false)
$this->bDebug = true;
else
$this->bDebug = false;
}
// Return name of the database provider being used.
function getDatabase(){
return $this->sDatabase;
}
// Returns true or false if $sDatabase is the database provider currently being used. Not case sensitive.
// $sDatabase Name of database provider to check
function usingDatabase($sDatabase){
if(strtolower($sDatabase) == $this->sDatabase)
return true;
else
return false;
}
// Make a connection to the database
// $sDBHost Host name that the database resides on. Can be a URL. Default 'localhost'
// $sDBName Name of database
// $sDBUser User name to connect to the database with
// $sDBPassword Password for user to connect to the datbase with
// $sDBPort Port that the database uses on host machine. Default 5432.
function connection($sDBHost = "localhost", $sDBName, $sDBUser, $sDBPassword, $sDBPort = "5432"){
switch($this->sDatabase){
case "mysql":
$this->dbi = mysql_connect($sDBHost, $sDBUser, $sDBPassword) or die("Could not connect to database");
mysql_select_db ($sDBName, $this->dbi);
break;
case "postgresql":
$this->dbi = pg_connect("host=" . $sDBHost . " dbname=" . $sDBName . " user=" . $sDBUser . " password=" . $sDBPassword)
or die("Could not connect");
break;
}
}
// Send a query to the database.
// $sQuery String containing query to send to the database
// $iResultID The result identifier will be saved in the $aResults array with this index.
// If you need to work with more then one result identifier then you will need to give the
// result identifier an index here so you can reference it later. Else it will be written over next query
// Default index 0.
function query($sQuery, $iResultID=0){
$this->sQuery = $sQuery;
if($this->bDebug)
echo "<div><font color=blue><b>SQL query:</b></font> " . str_replace(",",", ",htmlentities($sQuery)) . "</div>";
switch($this->sDatabase){
case "mysql": $this->aResults[$iResultID] = @mysql_query($sQuery, $this->dbi); break;
case "postgresql": $this->aResults[$iResultID] = @pg_exec($this->dbi, $sQuery); break;
}
}
// Check whether a result identifier is valid.
// $iResultID Index into $aResults to check the appropriate result. Default index = 0
// Returns: True on a valid result, false otherwise
function checkError($iResultID=0){
if(!$this->aResults[$iResultID])
return false;
else
return true;
}
// Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
// $iResultID Index into $aResults to use the appropriate result identifier
// $iResultType Number representing the type of array to return:
// 1 Associative indices only
// 2 Number indices only
// 3 Array with both associative and number indices
function fetchArray($iResultID=0, $iResultType=3){
if(!array_key_exists($iResultID, $this->aResults)){
echo "<p>Result identifier doesn't exist!</p>";
}
if(!$this->aResults[$iResultID])
trigger_error("Invalid result", E_USER_ERROR);
switch($this->sDatabase){
case "mysql": return mysql_fetch_array($this->aResults[$iResultID], $iResultType);
case "postgresql": return pg_fetch_array($this->aResults[$iResultID], "", $iResultType);
//trigger_error("PostgreSQL does not support fetching an array from a result identifier", E_USER_ERROR);break;
}
}
// Fetches one row of data from the result associated with the specified result identifier.
// The row is returned as an array. Each result column is stored in an array offset, starting at offset 0.
// Returns FALSE if there are no more rows.
// $iResultID Index into $aResults array to use the appropriate result identifier
function fetchRow($iResultID=0){
if(!array_key_exists($iResultID, $this->aResults)){
echo "<p>Result identifier doesn't exist!</p>";
}
if(!$this->aResults[$iResultID])
trigger_error("Invalid result", E_USER_ERROR);
switch($this->sDatabase){
case "mysql": $aRow = mysql_fetch_row($this->aResults[$iResultID]); break;
case "postgresql": $aRow = pg_fetch_row($this->aResults[$iResultID]); break;
}
return $aRow;
}
// Returns the name of the specified field index.
// $iResultID Index to a valid result identifier in $aResults
// $iIndex The numerical offset of the field.
function fieldName($iIndex=0, $iResultID=0){
if(!array_key_exists($iResultID, $this->aResults)){
echo "<p>Result identifier doesn't exist!</p>";
}
if(!$this->aResults[$iResultID])
trigger_error("Invalid result", E_USER_ERROR);
switch($this->sDatabase){
case "mysql": $sFieldName = mysql_field_name($this->aResults[$iResultID], $iIndex); break;
case "postgresql": $sFieldName = pg_fieldname($this->aResults[$iResultID], $iIndex); break;
}
return $sFieldName;
}
// Returns the number of rows in a result set. This command is only valid for SELECT statements.
// $iResultID Index to a valid result identifier in $aResults
function numRows($iResultID=0){
if(!array_key_exists($iResultID, $this->aResults)){
echo "<p>Result identifier doesn't exist!</p>";
}
if(!$this->aResults[$iResultID])
trigger_error("Invalid result", E_USER_ERROR);
switch($this->sDatabase){
case "mysql": $iRows = mysql_num_rows($this->aResults[$iResultID]); break;
case "postgresql": $iRows = pg_numrows($this->aResults[$iResultID]); break;
}
return $iRows;
}
// Get number of fields in result
// $iResultID Index to a valid result identifier in $aResults
function numFields($iResultID=0){
if(!array_key_exists($iResultID, $this->aResults)){
echo "<p>Result identifier doesn't exist!</p>";
}
if(!$this->aResults[$iResultID])
trigger_error("Invalid result", E_USER_ERROR);
switch($this->sDatabase){
case "mysql": $iNumFields = mysql_num_fields($this->aResults[$iResultID]); break;
case "postgresql": $iNumFields = pg_numfields($this->aResults[$iResultID]); break;
}
return $iNumFields;
}
// Appends the appropriate SQL syntax for limitting the number of rows returned by a query to $sSQL.
// $sSQL Valid SQL query. Should allready contain a 'where' clause
// $iOffset Offset from the first result record from which to return results from
// $iLimit Maximum number of records to return
function limitQuery($sSQL, $iOffset, $iLimit){
switch($this->sDatabase){
case "mysql": $sSQL = $sSQL . " limit $iOffset, $iLimit"; break;
case "postgresql": $sSQL = $sSQL . " limit $iLimit, $iOffset";break;
}
return $sSQL;
}
}
There's heaps of other PHP database functions you could add in there too... there the only ones I ever use though.
It works well though implementing it as a class... that way you can have nice neat code like:
$oSQL = new SQL("MySQL");
$oSQL->connection("localhost", "mydb", "adam", "password", "5432");
$oSQL->query("select * from table");
if($oSQL->checkError())
return false;
while(list($id) = $oSQL->fetchRow()){
echo $id;
}
etc.
Hope someone may find that intresting...
cya
-Adam 🙂