Saturday, 18 July 2009

Database Abstraction

For my shopping cart in the project, I will use a simple database abstraction library.

The database functions is stored in library/database.php.

These lines of code are using PHP database function directly :


require_once 'config.php';

function dbQuery($sql)
{
return mysql_query($sql) or die('Query failed. ' . mysql_error());
}

function dbAffectedRows()
{
global $dbConn;

return mysql_affected_rows($dbConn);
}

function dbFetchArray($result, $resultType = MYSQL_NUM)
{
return mysql_fetch_array($result, $resultType);
}

function dbFetchAssoc($result)
{
return mysql_fetch_assoc($result);
}

function dbFetchRow($result)
{
return mysql_fetch_row($result);
}

function dbFreeResult($result)
{
return mysql_free_result($result);
}

function dbNumRows($result)
{
return mysql_num_rows($result);
}

function dbSelect($dbName)
{
return mysql_select_db($dbName);
}
?>

Difference between Direct Function code and Abstraction code.

These codes use PHP database function directly :

$conn = mysql_connect($dbHost, $dbUser, $dbPass);
mysql_select_db($dbName);

$sql = "SELECT *
FROM tbl_product
ORDER BY pd_name";

$result = mysql_query($sql);

$products = array();
while ($row = mysql_fetch_assoc($result)) {
$products[] = $row;
}
?>

And this block of source code is using our database abstraction:

$sql = "SELECT *
FROM tbl_product
ORDER BY pd_name";

$result = dbQuery($sql);

$products = array();
while ($row = dbFetchAssoc(&$result)) {
$products[] = $row;
}
?>

No comments:

Post a Comment