-1

基本上我正在尝试创建一个类来处理数据库连接。我已经仔细检查以确保我的连接变量是正确的,并且如果我将它们直接插入 PHP 页面,它们就可以工作。但是当我这样称呼班级时:

require_once __DIR__ . 'includes/db_connect.php';
$db = new DB_CONNECT();

它不起作用。这是我的代码。也许我错过了一些东西。

<?php

// Class file to connect to database
class DB_CONNECT {

    // constructor
    function __construct()
    {
        // connection to database
        $this->connect();
    }

    // destructor
    function __destruct()
    {
        // disconnecting from database
        $this->close();
    }

    // Function for Database Connection
    function connect()
    {
        // import database connection variables
        require_once _DIR_ . '/db_config.php';

        // connection to mysql database
        $con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die (mysql_error());

        // selecting database
        $db = mysql_select_db(DB_DATABASE) or die (mysql_error()) or die (mysql_error());

        // returning connection cursor
        return $con;
    }

    // Function to close db connection
    function close()
    {
        // closing db connection
        mysql_close();
    }

}
?>
4

3 回答 3

1

connect()您的函数中有一个错字:

require_once _DIR_ . '/db_config.php';

应该:

require_once __DIR__ . '/db_config.php';

您需要双下划线,否则 PHP 将在服务器的根目录中查找配置文件。

于 2013-05-23T15:04:24.303 回答
0

尝试替换_DIR_dirname(__FILE__)

正如@jterry所说,不推荐使用mysql。

于 2013-05-23T15:08:49.097 回答
0

尝试这样的事情

    function connect(){
        $this->conn = mysqli_connect("localhost",$this->user,$this->password);
        if (!$this->conn){
            echo "No DB connection"; 
            exit;
        }
        $this->db = mysqli_select_db("DB_NAME");
        if (!$this->db){
            echo "Can't find DB";
            exit;
        }
于 2013-05-23T15:00:01.040 回答