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为新文件调用新的数据库连接。这是我的function.php。我现在想为user.php打电话。
答案 0 :(得分:0)
You can do this in user.php. First include the function.php at very top of the code after:
<?php
include "pathtofunction.php";
Where you want to call a new database connection do this:
$db=new Users();
And you need to create the field connect before to access it. Like this:After
class Users{
public $connect;
答案 1 :(得分:0)
这是我测试过的答案,首先你需要构建如下所示的Database类,你需要把它放在一个PHP文件中并从你的主页中包含它(可能是index.php页面)。然后,您需要从主页启动您的类的实例以连接到数据库PHP类,该类将连接到MySQL数据库的内置函数mysql_connect,在这篇伟大的文章中详细解释了代码:{{ 3}}
<?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);
}
}
?>