Hello all,
I found it useful to incapsulate database functions to some class to work with database transparently. However, classes produce lots of boring stuff like $a->... so I decided to do it the following manner:
1. You have a global variable $_db_environment to store settings. I think no one would normally use such awkward names so you won't have mistakingly redefine it :)
2. DB environment is an associative array in the form 'hash key' => 'handler data'. When you connect to a database using db_connect, a key based on host, file and user is generated using md5, associated with db_handle class and returned. Moreover, the last db is assumed default handle.
3. When calling 'db_' functions, you can pass the key you obtained from db_connect explicitly or the default key will be used.
4. When executing a query, you can specify a tag which will be further accociated with resource id. So you can simultaneously handle an arbitrary number of queries. If the tag is omitted, the 'default' tag is used.
5. When fetching the query, you can specify NO parameters at all, then default values will be used.
In brief:
// define function for simplicity
function connect() {
return db_connect('Interbase','localhost','/opt/db/dbdb.gdb','DBDB','bdbd',
array('CHARSET' => 'WIN1251')
);
}
// connect to Interbase
$ibh = connect();
// launch a default query
db_query('SELECT * FROM SOME_TABLE');
// while we have something, process it
while($row = db_fetch_array()) {
// launch another query
db_query('another','SELECT * FROM OTHER_TABLE WHERE ID='.$row['FIELD']);
// print something if we got record
if($another = db_fetch_array('another')) echo $another['ARTICLE'];
// free the query
db_free_result('another');
}
TODO:
1. Test the functions under all possible databases. (please help!)
2. Smart error handling.
3. Add parameter binding
|