mysqli_close()期望参数1为mysqli,给定为null

时间:2015-08-08 17:41:56

标签: php mysqli

您好我需要使用PHP连接mysql数据库,我的代码如下所示,

<?php
/**
 * A class file to connect to database

*/

class DB_CONNECT {  
// constructor
    function __construct() {   
    }

// destructor
    function __destruct() {    
 // closing db connection
        $this->close();
    }

 /**
     * Function to connect with database  
 */
    function connect() {

 // import database connection variables
    require_once __DIR__ . '/db_config.php';

 // Connecting to mysql database
    $con =  mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE) or die("Data base connection failed....! " . mysqli_error($con)); 
  // returing connection cursor
        return $con;
    }
  /**
     * Function to close db connection    
 */
    function close() {      
 // closing db connection
      mysqli_close($con);     
    }
}
?>

但我收到了警告

Warning: mysqli_close() expects parameter 1 to be mysqli, null given in db_connect.php on line 54

上面的代码有什么错误吗?

2 个答案:

答案 0 :(得分:3)

使$con成为函数之外的私有变量。

<?php

    /**
     * A class file to connect to database

    */


    class DB_CONNECT {

        private $con = null;

    // constructor
        function __construct() {

        }


    // destructor
        function __destruct() {

     // closing db connection
            $this->con = null;
        }


     /**
         * Function to connect with database

     */
        function connect() {

     // import database connection variables
        require_once __DIR__ . '/db_config.php';


     // Connecting to mysql database
        $this->con =  mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE) or die("Data base connection failed....! " . mysqli_error($con)); 


      // returing connection cursor
            return $this->con;
        }



      /**
         * Function to close db connection

     */
        function close() {

     // closing db connection
          mysqli_close($this->con);

        }
    }
    ?>

然后你可以在整个班级访问它。同样在构造函数中调用connect函数以确保它所做的第一件事就是连接。

修改1

从我所看到的,您的命名约定也有点过时了。您的班级名称DB_CONNECT看起来像const,因为这是您在db_config.php中指定的名称。

答案 1 :(得分:0)

我可以看到在$con函数中没有初始化close()变量,最好的选择是使用make这样的整个类。

<?php

class DB_CONNECT {  

public $con;

    function __construct() {  

      $this->connect(); 
    }


    function __destruct() {    

        $this->close();
    }


    function connect() {

 // import database connection variables
    require_once __DIR__ . '/db_config.php';

 // Connecting to mysql database
    $con =  mysqli_connect(DB_SERVER,DB_USER,DB_PASSWORD,DB_DATABASE) or die("Data base connection failed....! " . mysqli_error($con)); 
  // returing connection cursor
    $this->con=$con;
        return $con;
    }

    function close() {      
        mysqli_close($this->con);     
    }
}
?>

正如您所看到的,我创建了一个类级变量$con并使用$this指针我已在$con函数内初始化了类级变量connect(),并且close()函数它是相同的类级变量,以获取关闭数据库连接的正确参数。