Given your working with procedural code and *should avoid global variables I would recommend using statics.
PHP Code:
function getDb($conn=null) { /* probably a bad name but I never do this and have no idea what to call it... I think drupal uses get for the same concept without OO */
static $db;
if($conn !== null) {
$db = $conn;
}
return $db;
}
Upon setting up the connection call the function passing the db resource and when you would like to get it after call the function without passing an arguments:
PHP Code:
// Make the connection.
$dbc = @mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die('Could not connect to database. Contact System Administrator.');
// set the connection reference
getDb($dbh);
PHP Code:
function getNumberOfPosts($id) {
$dbc = getDb(); /* now the function has a dependency on getDb() but I believe this is good method given the procedural nature of the code */
if (!$res = $dbc->query('SELECT COUNT(id) AS total FROM posts WHERE id = ' . $id)) {
die('MySQL Error: ' . $res->error);
}
return $res->num_rows;
}
In my opinion that is still really dirty and undesirable but it is probably the best solution aside from creating an object-oriented data access layer which would require completely changing existing architecture.
The other solution is passing the connection as an argument to every function that is dependent on it.
PHP Code:
function getNumberOfPosts($id,$dbc) { /* all data access function would require passing the connection... using a function seems better */
if (!$res = $dbc->query('SELECT COUNT(id) AS total FROM posts WHERE id = ' . $id)) {
die('MySQL Error: ' . $res->error);
}
return $res->num_rows;
}
At least by using a function to get and set the connection some code repetition can be eliminated.
Bookmarks