我需要使用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
上面的代码有错误吗?
将$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
中指定它们的方式。
我可以看到有一个$con
变量没有在close()
函数内初始化,最好的选择是使用使整个类像这样。
<?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
指针,我已经在connect()
函数内初始化了类级别变量$con
,并且在close()
函数中,它是相同的类级别变量,以获得正确的参数来关闭数据库连接。