我试图通过PHP中的OOP进程连接到php myadmin中的mysql数据库。但我的连接没有创建。我在phpmyadmin中检查了我的数据库名称也没问题。但不知道为什么我的连接没有被创建。我的代码就是我的代码。
<?php
class db{
public $host = 'localhost';
public $username = 'root';
public $password = '';
public $dbname = 'oop';
public function __construct(){
$con = new mysqli($this->host,$this->username,$this->password,$this->dbname);
}
}
if(isset($con)){
echo "<center><h1 style='color:green;'>Db is conected</h1></center>";
}else{
echo "<center><h1 style='color:red;'>Db is not conected</h1></center>";
}
$obj = new db;
?>
但我得到&#34; Db没有连接&#34;。请纠正我在哪里犯了错误
答案 0 :(得分:1)
在课堂上,创建一个新属性。例如。
public $con;
然后在你的构造函数中,将它作为
$this->con = new mysqli('','','',''); //database credentials
然后您可以在
中检查连接是否成功if ( $this->con === false) { // add in construct function
//connection failed
}
或者您可以创建类的实例并检查连接是否成功
$obj = new db(); // __construct() has already been executed
if ( $obj->con === false) {
//connection failed
}
答案 1 :(得分:0)
将此行$con = new mysqli($this->host,$this->username,$this->password,$this->dbname);
更改为$this->con = new mysqli($this->host,$this->username,$this->password,$this->dbname);
并在访问之前创建实例$obj = new db;
。所以像这样改变你的代码
$obj = new db;
if($obj->con!=null){
echo "<center><h1 style='color:green;'>Db is conected</h1></center>";
}else{
echo "<center><h1 style='color:red;'>Db is not conected</h1></center>";
}