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