PHP MySQL 封装类是一种设计模式,用于将数据库操作逻辑封装在一个类中,以便于代码的复用和维护。通过封装类,可以简化数据库连接、查询、插入、更新和删除等操作。
常见的 PHP MySQL 封装类有以下几种类型:
以下是一个简单的 PHP MySQL 封装类示例:
<?php
class Database {
private $host = "localhost";
private $username = "root";
private $password = "";
private $dbname = "mydatabase";
private $conn;
public function __construct() {
try {
$this->conn = new PDO("mysql:host=$this->host;dbname=$this->dbname", $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
}
public function query($sql) {
try {
$stmt = $this->conn->query($sql);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
echo "Query failed: " . $e->getMessage();
}
}
public function insert($table, $data) {
$keys = implode(', ', array_keys($data));
$values = ':' . implode(', :', array_keys($data));
$sql = "INSERT INTO $table ($keys) VALUES ($values)";
try {
$stmt = $this->conn->prepare($sql);
$stmt->execute($data);
return true;
} catch (PDOException $e) {
echo "Insert failed: " . $e->getMessage();
}
}
public function update($table, $data, $where) {
$set = '';
foreach ($data as $key => $value) {
$set .= "$key = :$key,";
}
$set = rtrim($set, ',');
$sql = "UPDATE $table SET $set WHERE $where";
try {
$stmt = $this->conn->prepare($sql);
$stmt->execute($data);
return true;
} catch (PDOException $e) {
echo "Update failed: " . $e->getMessage();
}
}
public function delete($table, $where) {
$sql = "DELETE FROM $table WHERE $where";
try {
$stmt = $this->conn->prepare($sql);
$stmt->execute();
return true;
} catch (PDOException $e) {
echo "Delete failed: " . $e->getMessage();
}
}
}
?>
try-catch
块捕获并处理异常。prepare
和 execute
方法)来防止 SQL 注入。通过以上封装类和相关方法,可以有效地管理和操作数据库,提高代码的可维护性和安全性。
领取专属 10元无门槛券
手把手带您无忧上云