class Users {
function __construct(){
//database configuration
$dbServer = 'localhost'; //Define database server host
$dbUsername = 'abc'; //Define database username
$dbPassword = 'def'; //Define database password
$dbName = 'ghi'; //Define database name
//connect databse
$con = mysqli_connect($dbServer,$dbUsername,$dbPassword,$dbName);
if(mysqli_connect_errno()){
die("Failed to connect with MySQL: ".mysqli_connect_error());
}else{
$this->connect = $con;
}
}
}如何使用this.This为新文件调用新的数据库连接是我的function.php。我现在想把这叫做user.php。
发布于 2015-12-14 17:54:14
您可以在user.php中这样做。首先,将function.php放在代码的最上面,然后是:
<?php
include "pathtofunction.php";如果要调用新的数据库连接,请执行以下操作:
$db=new Users();您需要先创建字段连接才能访问它。就像这样:之后
class Users{
public $connect;发布于 2016-01-27 19:08:31
下面是我的测试答案,首先您需要构建数据库类,如下所示,您需要将它放入一个PHP文件中,并将其包含在您的主页(可能是index.php页面)中。然后,您需要从主页启动类的一个实例,以连接到数据库PHP类,该类将连接到MySQL数据库内建函数mysql_connect,代码在这篇伟大的文章中有详细的说明:Www.muwasaba.com/php-数据库-连接。
<?php
// Class definition
class Database{
// The constructor function
public function __construct(){
// The properties
$this->host = "your_DB_host_address";
$this->login = "your_DB_login_name";
$this->password = "your_DB_password";
$this->name = "your_DB_name";
// The methods
$this->connect();
$this->select();
}
// The connect function
private function connect(){
$this->connection = mysql_connect($this->host, $this->login, $this->password) or die("Sorry! Cannot connect to the database");
}
// The select function
private function select(){
mysql_select_db($this->name, $this->connection);
}
}
?>https://stackoverflow.com/questions/34273393
复制相似问题