0

要打开数据库连接,我目前使用此类方法:

    function openDB() {


// 1. Create a database connection
$conn = mysqli_connect("x" , "x", "x","x");
if (!$conn)
{
    $this->error_msg = "connection error could not connect to the database:! ";  
    return false;
}
$this->conn = $conn;
return true;
}

但是,我想改用我的配置文件

require("assets/configs/db_config.php");

显然这个文件包含了数据库连接信息。

我怎么能摆脱

$conn = mysqli_connect("x" , "x", "x","x");

并简单地制作 $conn 并让它使用 DB_Config.php 代替?

4

2 回答 2

0

Change

function openDB()

to

function openDB($server, $user, $pass, $dbName)

and pass those variables to mysqli_connect

and pass data from included file.I suppose, you have them in some sort of constants or defines.

Also, it would be good idea to haveDB connection somewhere globally.

于 2013-07-29T16:18:25.407 回答
0

为您的配置文件返回您需要的值的数组

 return array("host"=>"example.com", "dbname"=>"mydb", "username"=>"dbuser", "password"=>"secret");

然后在您的 openDb 函数中执行此操作。

function openDB() {
  // 1. Create a database connection
  $config = include("/path/to/config.php");
  $conn = mysqli_connect($config["host"] , $config["username"], $config["password"],$config["dbname"]);
  if (!$conn)
  {
    $this->error_msg = "connection error could not connect to the database:! ";  
    return false;
  }
  $this->conn = $conn;
  return true;
}
于 2013-07-29T16:21:41.327 回答