Monday, August 16, 2010

Database in PHP

I am always troubled by the code needed to connect to database and send a query. Previously I created a class to return the whole result set of odbc_exec so that it could accommodate the "update" and "select" query. But it still bothers me a lot to do a loop (odbc_fetch_row) for "select" query. I have discovered that using a callback function, I could actually avoid defining the loop itself. Although this will limit the code to just "select" query, it does make the whole database access code become just two line (actually three if you put the query statement as a variable).

The following is the class.

class myclass {
/*
Use extract($db_j); in $callback to export the keys and values of the array as variable
*/
public function run_sql_cb($sql,$db_con,$db_usr,$db_pwd,$callback){
if ($db_obj)
$result=odbc_next_result($db_obj);
$conn = odbc_connect($db_con,$db_usr,$db_pwd);
if (!$conn){
exit("Connection failed: " . $conn);
}
$db_obj=odbc_exec($conn,$sql);
if (!$db_obj){
exit("Sql failed");
}
while ($db_j = odbc_fetch_array($db_obj)) {
$callback($db_j);
}

}
}
The sample callback routine is as below

function caller($myobj){
extract($myobj);
echo $Mycount." ".$CNT."
";
}

and the calling code

$mc= new myclass;
$sql="select Mycount,CNT from sample.csv";
$dbclass->run_sql_cb($sql,"tester","","","caller");

The class is a simple routine to connect to a database using the ODBC connect code. I added the callback code by adding a callback on the dataset loop. The callback is done by just adding the callback function name to the class function. The class function will in turn just add a () to the variable passed and it becomes a callback function.

In the dataset loop, I use odbc_fetch_array so that I could pull a recordset as an associative array. I passed this array to the callback function.

In the callback function, I used a extract() function. Extract() function will take the associative array and make the key as variable name and the key value as the variable value. Since it is in the function, the scope of the variable is limited to the function thus does not affect the main routine variables.

The rest of the callback function is then up to you to add whatever code to manipulate the recordset.

No comments:

Post a Comment