简体   繁体   中英

How can I avoid storing database credentials in multiple places in the code?

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?

为什么不拥有一个“ config.php”来声明您将使用的所有变量,例如用户名,数据库,服务器,其他可能与站点相关的设置等。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM