PHP数据库操作对象,让你在使用php操作数据库的时候更方便、更得心应手。本位为你提供一个完善的PHP数据库操作类,它提供了新建数据库、新建表、读取、插入、更新和删除等功能。且代码的设计注重安全性、稳定性、高效性和易用性。
一、PHP操作Mysql的对象
<?php
/**
* 数据库操作类
* 提供安全、稳定、高效的数据库操作功能
*/
class Database {
private $host;
private $username;
private $password;
private $database;
private $charset;
private $pdo;
private $error;
private $isConnected = false;
/**
* 构造函数
* @param string $host 数据库主机
* @param string $username 用户名
* @param string $password 密码
* @param string $database 数据库名
* @param string $charset 字符集,默认utf8mb4
*/
public function __construct($host, $username, $password, $database = '', $charset = 'utf8mb4') {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->charset = $charset;
}
/**
* 连接到数据库
* @return bool 连接成功返回true,否则返回false
*/
public function connect() {
try {
$dsn = "mysql:host={$this->host};charset={$this->charset}";
if (!empty($this->database)) {
$dsn .= ";dbname={$this->database}";
}
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_PERSISTENT => false,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$this->charset}"
];
$this->pdo = new PDO($dsn, $this->username, $this->password, $options);
$this->isConnected = true;
return true;
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 关闭数据库连接
*/
public function disconnect() {
$this->pdo = null;
$this->isConnected = false;
}
/**
* 创建数据库
* @param string $database 数据库名
* @return bool 成功返回true,否则返回false
*/
public function createDatabase($database) {
if (!$this->isConnected) {
$this->connect();
}
try {
$sql = "CREATE DATABASE IF NOT EXISTS `{$database}` CHARACTER SET {$this->charset} COLLATE utf8mb4_unicode_ci";
$this->pdo->exec($sql);
return true;
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 选择数据库
* @param string $database 数据库名
* @return bool 成功返回true,否则返回false
*/
public function selectDatabase($database) {
if (!$this->isConnected) {
$this->connect();
}
try {
$this->pdo->exec("USE `{$database}`");
$this->database = $database;
return true;
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 创建数据表
* @param string $table 表名
* @param array $columns 列定义数组
* @return bool 成功返回true,否则返回false
*
* 示例:
* $columns = [
* "id INT(11) AUTO_INCREMENT PRIMARY KEY",
* "name VARCHAR(255) NOT NULL",
* "email VARCHAR(255) NOT NULL UNIQUE",
* "created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
* ];
*/
public function createTable($table, $columns) {
if (!$this->isConnected) {
$this->connect();
}
if (empty($columns)) {
$this->error = "必须至少定义一个列";
return false;
}
try {
$columnsSql = implode(", ", $columns);
$sql = "CREATE TABLE IF NOT EXISTS `{$table}` ({$columnsSql}) ENGINE=InnoDB DEFAULT CHARSET={$this->charset}";
$this->pdo->exec($sql);
return true;
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 插入数据
* @param string $table 表名
* @param array $data 要插入的数据关联数组
* @return int|bool 成功返回插入的ID,失败返回false
*/
public function insert($table, $data) {
if (!$this->isConnected) {
$this->connect();
}
if (empty($data)) {
$this->error = "插入数据不能为空";
return false;
}
try {
$columns = implode("`, `", array_keys($data));
$placeholders = ":" . implode(", :", array_keys($data));
$sql = "INSERT INTO `{$table}` (`{$columns}`) VALUES ({$placeholders})";
$stmt = $this->pdo->prepare($sql);
$stmt->execute($data);
return $this->pdo->lastInsertId();
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 查询数据
* @param string $table 表名
* @param array $conditions 查询条件关联数组
* @param string $fields 要查询的字段,默认为*
* @param string $order 排序条件
* @param int $limit 限制返回数量
* @param int $offset 偏移量
* @return array|bool 成功返回结果数组,失败返回false
*/
public function select($table, $conditions = [], $fields = "*", $order = "", $limit = 0, $offset = 0) {
if (!$this->isConnected) {
$this->connect();
}
try {
$whereClause = "";
$params = [];
if (!empty($conditions)) {
$whereParts = [];
foreach ($conditions as $key => $value) {
$whereParts[] = "`{$key}` = :{$key}";
$params[":{$key}"] = $value;
}
$whereClause = "WHERE " . implode(" AND ", $whereParts);
}
$sql = "SELECT {$fields} FROM `{$table}` {$whereClause}";
if (!empty($order)) {
$sql .= " ORDER BY {$order}";
}
if ($limit > 0) {
$sql .= " LIMIT {$limit}";
if ($offset > 0) {
$sql .= " OFFSET {$offset}";
}
}
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return $stmt->fetchAll();
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 更新数据
* @param string $table 表名
* @param array $data 要更新的数据关联数组
* @param array $conditions 更新条件关联数组
* @return int|bool 成功返回受影响的行数,失败返回false
*/
public function update($table, $data, $conditions) {
if (!$this->isConnected) {
$this->connect();
}
if (empty($data)) {
$this->error = "更新数据不能为空";
return false;
}
if (empty($conditions)) {
$this->error = "更新条件不能为空";
return false;
}
try {
$setParts = [];
$setParams = [];
foreach ($data as $key => $value) {
$setParts[] = "`{$key}` = :set_{$key}";
$setParams[":set_{$key}"] = $value;
}
$whereParts = [];
$whereParams = [];
foreach ($conditions as $key => $value) {
$whereParts[] = "`{$key}` = :cond_{$key}";
$whereParams[":cond_{$key}"] = $value;
}
$sql = "UPDATE `{$table}` SET " . implode(", ", $setParts) .
" WHERE " . implode(" AND ", $whereParts);
$stmt = $this->pdo->prepare($sql);
$stmt->execute(array_merge($setParams, $whereParams));
return $stmt->rowCount();
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 删除数据
* @param string $table 表名
* @param array $conditions 删除条件关联数组
* @return int|bool 成功返回受影响的行数,失败返回false
*/
public function delete($table, $conditions) {
if (!$this->isConnected) {
$this->connect();
}
if (empty($conditions)) {
$this->error = "删除条件不能为空";
return false;
}
try {
$whereParts = [];
$params = [];
foreach ($conditions as $key => $value) {
$whereParts[] = "`{$key}` = :{$key}";
$params[":{$key}"] = $value;
}
$sql = "DELETE FROM `{$table}` WHERE " . implode(" AND ", $whereParts);
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
return $stmt->rowCount();
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 执行原始SQL查询
* @param string $sql SQL语句
* @param array $params 参数数组
* @return array|int|bool 对于SELECT返回结果数组,对于INSERT/UPDATE/DELETE返回受影响行数,失败返回false
*/
public function query($sql, $params = []) {
if (!$this->isConnected) {
$this->connect();
}
try {
$stmt = $this->pdo->prepare($sql);
$stmt->execute($params);
// 判断查询类型
$firstWord = strtoupper(strtok(trim($sql), " "));
if ($firstWord === 'SELECT' || $firstWord === 'SHOW' || $firstWord === 'DESCRIBE') {
return $stmt->fetchAll();
} else {
return $stmt->rowCount();
}
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 开始事务
* @return bool 成功返回true,否则返回false
*/
public function beginTransaction() {
if (!$this->isConnected) {
$this->connect();
}
try {
return $this->pdo->beginTransaction();
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 提交事务
* @return bool 成功返回true,否则返回false
*/
public function commit() {
try {
return $this->pdo->commit();
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 回滚事务
* @return bool 成功返回true,否则返回false
*/
public function rollBack() {
try {
return $this->pdo->rollBack();
} catch (PDOException $e) {
$this->error = $e->getMessage();
return false;
}
}
/**
* 获取错误信息
* @return string 错误信息
*/
public function getError() {
return $this->error;
}
/**
* 检查是否已连接
* @return bool 已连接返回true,否则返回false
*/
public function isConnected() {
return $this->isConnected;
}
/**
* 防止对象被克隆
*/
private function __clone() {}
}
// 使用示例
/*
// 创建数据库实例
$db = new Database('localhost', 'root', 'password');
// 连接数据库
if (!$db->connect()) {
die("连接失败: " . $db->getError());
}
// 创建数据库
if (!$db->createDatabase('my_app')) {
die("创建数据库失败: " . $db->getError());
}
// 选择数据库
if (!$db->selectDatabase('my_app')) {
die("选择数据库失败: " . $db->getError());
}
// 创建表
$columns = [
"id INT(11) AUTO_INCREMENT PRIMARY KEY",
"name VARCHAR(255) NOT NULL",
"email VARCHAR(255) NOT NULL UNIQUE",
"password VARCHAR(255) NOT NULL",
"created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
];
if (!$db->createTable('users', $columns)) {
die("创建表失败: " . $db->getError());
}
// 插入数据
$userId = $db->insert('users', [
'name' => '张三',
'email' => 'zhangsan@example.com',
'password' => password_hash('123456', PASSWORD_DEFAULT)
]);
if ($userId === false) {
die("插入数据失败: " . $db->getError());
}
echo "插入成功,用户ID: " . $userId . "<br>";
// 查询数据
$users = $db->select('users', ['name' => '张三'], '*', 'id DESC', 10);
if ($users === false) {
die("查询数据失败: " . $db->getError());
}
echo "查询结果: <pre>";
print_r($users);
echo "</pre>";
// 更新数据
$affectedRows = $db->update('users', ['name' => '李四'], ['id' => $userId]);
if ($affectedRows === false) {
die("更新数据失败: " . $db->getError());
}
echo "更新了 {$affectedRows} 条记录<br>";
// 删除数据
$affectedRows = $db->delete('users', ['id' => $userId]);
if ($affectedRows === false) {
die("删除数据失败: " . $db->getError());
}
echo "删除了 {$affectedRows} 条记录<br>";
// 关闭连接
$db->disconnect();
*/
?>二、该代码的设计特点
1. 安全性:
· 使用PDO预处理语句防止SQL注入
· 参数化查询确保数据安全
· 输入验证和错误处理
2. 稳定性:
· 完善的异常处理机制
· 连接状态管理
· 事务支持保证数据一致性
3. 高效性:
· 使用PDO扩展,性能优异
· 连接复用
· 灵活的查询方法
4. 易用性:
· 简洁的API设计
· 详细的文档注释
· 丰富的使用示例
三、该代码使用说明
1. 实例化数据库对象:
$db = new Database('localhost', 'username', 'password');2. 连接数据库:
if (!$db->connect()) {
die("连接失败: " . $db->getError());
}3. 创建数据库:
$db->createDatabase('database_name');4. 选择数据库:
$db->selectDatabase('database_name');5. 创建表:
$columns = [
"id INT(11) AUTO_INCREMENT PRIMARY KEY",
"name VARCHAR(255) NOT NULL",
// 更多列定义...
];
$db->createTable('table_name', $columns);6. 插入数据:
$id = $db->insert('table_name', [
'column1' => 'value1',
'column2' => 'value2'
]);7. 查询数据:
$results = $db->select('table_name',
['condition_column' => 'value'],
'*',
'id DESC',
10,
0);8. 更新数据:
$affected = $db->update('table_name',
['column1' => 'new_value'],
['id' => 1]);9. 删除数据:
$affected = $db->delete('table_name', ['id' => 1]);10. 使用事务:
$db->beginTransaction();
// 执行多个操作...
if ($everythingOk) {
$db->commit();
} else {
$db->rollBack();
}四、该代码使用注意事项
1. 在生产环境中,请确保数据库凭据的安全存储
2. 对于高并发应用,考虑使用连接池技术
3. 定期备份重要数据
4. 根据实际需求调整PDO选项和MySQL配置
这个数据库操作类提供了基本但完整的数据库操作功能,您可以很容易根据实际项目需求进行扩展和优化,十分容易上手!








