我是新人下面是尝试与数据库进行交互的开始。如果语法不正确,请让我知道,它似乎在我的本地主机上工作。
我想我可以输入class Database extends Mysqli
,对吗?这样就可以直接访问mysql的方法,而不是通过在类本身中创建的实例。那样会比我所做的更好吗?
class Database {
#The variable that stores the database handle
public $db;
#The Database objects's datbase parameters
public $host;
public $user;
public $password;
public $database;
#creates a Database object with the required databases details
public function __construct($host, $user, $password, $database) {
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->database = $database;
}
#Stores the database handle as a var $db of the Database instance
public function connect() {
if ($this->db = new Mysqli($this->host, $this->user, $this->password, $this->database)) {
if ($this->db->connect_errno) {
echo "No connection could be made <br/>";
} else {
echo "database succesfully connected <br/>";
}
}
}
}
如果您的class Database
表示数据库句柄,那么它不应该将其公开:
#The variable that stores the database handle
public $db;
否则你不会封装那个细节,因此你根本不需要你的类。
接下来,当你开始写类时,echo
不属于那里:
if ($this->db = new Mysqli($this->host, $this->user, $this->password, $this->database)) {
if ($this->db->connect_errno) {
echo "No connection could be made <br/>";
} else {
echo "database succesfully connected <br/>";
}
}
因为类由通过返回值返回的方法组成,而不是通过标准输出返回。相反,你想在这里抛出一个异常。这也是mysql的一个特性,因此,您不需要自己编写错误处理代码来开始:
- 在MySQLi 中将查询错误转化为异常
在解决了这些或多或少明显的问题之后,您要问自己是否应该继承mysqli
而不是聚合它。
mysqli
的标准功能,因此我建议完全放弃这个类,因为代码看起来多余。所以我的回答是:两者都不是。我看没有理由你的Database
类,你只是可以使用mysqli
代替。