PHP操作MySQL封装是指将MySQL数据库的操作(如连接、查询、插入、更新、删除等)封装成类或函数,以便在项目中重复使用,提高代码的可维护性和可读性。
常见的PHP操作MySQL封装方式有:
适用于需要频繁进行数据库操作的Web应用、API服务、后台管理系统等。
<?php
class MySQLDB {
private $host;
private $username;
private $password;
private $dbname;
private $conn;
public function __construct($host, $username, $password, $dbname) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->dbname = $dbname;
$this->connect();
}
private function connect() {
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->dbname);
if ($this->conn->connect_error) {
die("连接失败: " . $this->conn->connect_error);
}
}
public function query($sql) {
return $this->conn->query($sql);
}
public function escape($string) {
return $this->conn->real_escape_string($string);
}
public function close() {
$this->conn->close();
}
}
// 使用示例
$db = new MySQLDB('localhost', 'root', 'password', 'testdb');
$result = $db->query("SELECT * FROM users");
while ($row = $result->fetch_assoc()) {
echo $row['name'] . "<br>";
}
$db->close();
?>
prepare
和execute
方法)或手动转义用户输入。通过以上封装和示例代码,可以有效地管理和操作MySQL数据库,提高开发效率和代码质量。
领取专属 10元无门槛券
手把手带您无忧上云