The user ‘Chacha102’ posted the following code in response to this question back in 2010. I like his code (displayed below), but would like suggestions on how to avoid having the database connection credentials appearing in multiple places in the code.
Here is his code:
$cb_db = new cb_db(USER, PASSWORD, NAME, HOST);
$cb_user = new cb_user($cb_db);
class cb_user {
public __construct(cb_db $database)
{
$this->database = $database
}
protected function find_by_sql( $sql ) {
$this->database = new cb_db(USER, PASSWORD, NAME, HOST);
$result_set = $cb_db->query( $sql );
$object_array = array();
while( $row = $cb_db->fetch_array( $result_set ) ) {
$object_array[] = self::instantiate( $row );
}
return $object_array;
}
}
The problem is that I will have many classes and functions and don’t want to have the username a password hard coded into each of them. I’d prefer it if when necessary it can be updated in just one place.
What is the best way to accomplish this please?
Why not have a “config.php” which declares all the variables you will use, such as username, database, server, other settings maybe relevant to the site etc.