PHP函数和数据库连接

时间:2016-05-07 11:57:14

标签: php function connection

我试图保留一个用于PHP连接的文件,而不是在每个页面上使用mysqli_connect。

我有一个config.ini文件,其中包含Db凭据,我在php文件中调用此文件db_connect.php db_connect.php的代码如下:

//stores hostname or the server name
$hostName;
//username for the database
$userName;
//password for the database
$password;
//database name
$dbName;

$ini = parse_ini_file('../../config/config.ini');   
while(list($key,$value) = each($ini))
{
    if($key == 'hostName')
    {
        $hostName = $value; //retrieving value of host name.
    }
    else if($key == 'userName')
    {
        $userName = $value; //retrieving database user name
    }
    else if($key == 'password')
    {
        $password = $value; //retrieving database password
    }
    else if($key == 'dbName')
    {
        $dbName = $value;   //retrieving database name.
    }
}
$connectobject1 = new mysqli($hostName, $userName, $password, $dbName);
if ($connectobject1->connect_errno) 
{
    echo "Connection Failed";
    exit();
}

使用上面的代码,我能够创建与数据库的连接。现在,当我在index.php文件中包含db_connect.php时,我使用require_once' db_connect.php'但是在index.php我的函数执行时问题就开始了。这些函数无法访问连接字符串。我的index.php代码示例如下:

//Creating DB connection
require_once '../connect/db_connect.php';

//Checking DB connection
if(!$connectobject1) 
{
    //connection to DB failed
    header('Location: /pages/error/error.php?id=0'); 
    exit();
}

function checkuser($UserID, $connectobject1)
{

    //function code
}

我已经读到使用全局连接不是一个好习惯。

如何继续我的联系?

1 个答案:

答案 0 :(得分:0)

使用这样的文件..

config.php文件,其中包含服务器详细信息

 <?php

    // PHP Database Constants
    // Database Constants
        defined('DB_SERVER') ? null : define("DB_SERVER", "127.0.0.1");
        defined('DB_PORT') ? null : define("DB_PORT", "8889");
        defined('DB_USER')   ? null : define("DB_USER", "popat234");
        defined('DB_PASS')   ? null : define("DB_PASS", "4JfQuuQnzU6yfPdm");
        defined('DB_NAME')   ? null : define("DB_NAME", "demo");

    ?>

database.php将具有连接设置

<?php

require_once ('config.php');

class MYSQLDatabase {

    private $connection;

  function __construct() {
    $this->open_connection();
  }

  public function open_connection() {
    $this->connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME, DB_PORT);
    if(mysqli_connect_errno()) {
      die("Database connection failed: " . 
           mysqli_connect_error() . 
           " (" . mysqli_connect_errno() . ")"
      );
    }
  }