以类的形式创建单独的连接文件

时间:2016-07-19 08:38:50

标签: php

我现在创建了单独的连接文件,我想在类表单中更改它。 我的代码在这里,

<?php 
$servername="localhost";
$username="dd";
$password="*******";
$database="Db";

class Connection
{
    function connect()
    { 
        $con = mysql_connect($servername,$database,$username,$password) || die("Error connecting to database");
        mysql_select_db("dd_KrishnaDb") or die ("database selection problem");  


    }
}
?>

现在当我在index.php文件中包含这个文件时,它没有在index.php文件中建立连接。

<?php
include_once ('Connection.php');
     $db = new Connection();
  ?>

我因用户'''localhost'错误而拒绝访问。所以请告诉我我的代码有什么问题。

2 个答案:

答案 0 :(得分:1)

Connection.php文件

中尝试此操作
class Connection
{
    public function __construct(){
        $this->servername   = 'localhost';
        $this->username     = 'root';
        $this->password     = 'xxxxxxxxx';
        $this->database     = 'myDB';
    }
    public function connect()
    {
        $conn =  mysqli_connect($this->servername, $this->username, $this->password,$this->database);
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        }
    }
}

答案 1 :(得分:0)

就像有人在这里指出的那样; mysql函数正在消失......这意味着,是时候进行升级了......最好是PDO。这是你的课程可能是什么样的(假设你走的是PDO路线)。

    <?php
        /**
         * FILENAME: Connection.php
         */

        // IT IS PREFERABLE TO HAVE A SEPARATE FILE FOR THIS AND THEN INCLUDE IT
        // DATABASE CONNECTION CONFIGURATION:
        defined("HOST")    or define("HOST",   "localhost");  // YOUR HOSTNAME
        defined("DBASE")   or define("DBASE",  "Db");         // YOUR DB NAME
        defined("USER")    or define("USER",   "dd");         // YOUR USERNAME
        defined("PASS")    or define("PASS",   "root");       // YOUR PASSWORD

        class Connection {

            /***
             * @var \PDO
             */
            private static $dbHandle;

            public static function connect(){
                if(!isset(self::$dbHandle)){
                    self::$dbHandle = self::getInstance();
                }
                return self::$dbHandle;
            }

            private static function getInstance(){
                try {
                    self::$dbHandle = new \PDO('mysql:host='.HOST.';dbname='. DBASE,USER,PASS);
                    self::$dbHandle->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
                    return self::$dbHandle;
                }catch(\PDOException $e){
                    throw new \Exception($e->getMessage());
                }
            }
        }

    ?>

现在,在您的脚本中,您可以包含Connection.php文件并获取如下所示的数据库连接句柄:

    <?php
        include_once ('Connection.php');
        $db     = Connection::connect(); // GET THE DB CONNECTION HANDLE

        var_dump($db);  // DUMPS THE PDO OBJECT...
    ?>