在类方法中打开DB连接

时间:2013-07-29 16:15:06

标签: php

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

    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?

2 个答案:

答案 0 :(得分:0)

更改

function openDB()

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

并将这些变量传递给mysqli_connect

并从包含的文件传递数据。我想,你可以在某种常量或定义中使用它们。

此外,最好在全球范围内进行数据库连接。

答案 1 :(得分: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;
}