php 封装pdo
时间: 2023-07-19 19:10:42 浏览: 143
好的,下面是一个简单的 PHP PDO 封装类的示例:
```php
class Database {
private $host = "localhost";
private $user = "username";
private $password = "password";
private $database = "database";
private $charset = "utf8mb4";
private $pdo;
public function __construct() {
$dsn = "mysql:host={$this->host};dbname={$this->database};charset={$this->charset}";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$this->pdo = new PDO($dsn, $this->user, $this->password, $options);
}
public function query($sql, $params = []) {
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return $stmt;
}
public function fetchAll($sql, $params = []) {
$stmt = $this->query($sql, $params);
return $stmt->fetchAll();
}
public function fetch($sql, $params = []) {
$stmt = $this->query($sql, $params);
return $stmt->fetch();
}
public function insert($table, $data) {
$keys = array_keys($data);
$values = array_values($data);
$placeholders = implode(',', array_fill(0, count($values), '?'));
$sql = "INSERT INTO $table (" . implode(',', $keys) . ") VALUES ($placeholders)";
$this->query($sql, $values);
return $this->pdo->lastInsertId();
}
public function update($table, $data, $where) {
$set = [];
$values = [];
foreach ($data as $key => $value) {
$set[] = "$key = ?";
$values[] = $value;
}
$sql = "UPDATE $table SET " . implode(',', $set) . " WHERE $where";
return $this->query($sql, $values)->rowCount();
}
public function delete($table, $where) {
$sql = "DELETE FROM $table WHERE $where";
return $this->query($sql)->rowCount();
}
}
```
这个类封装了 PDO,包含了常用的查询操作,如 query、fetchAll、fetch,以及增删改操作,如 insert、update、delete。你可以根据自己的需要进行扩展。使用时,只需要实例化这个类,并调用相应的方法即可。例如:
```php
$db = new Database();
$rows = $db->fetchAll("SELECT * FROM table WHERE id = ?", [1]);
```
这个示例会查询一个 ID 为 1 的记录,并返回一个数组。你可以根据需求进行修改。
阅读全文