阅读量:0
要通过PHP和MySQL类管理数据库,你可以创建一个PHP类,用于连接、查询、插入、更新和删除数据
- 创建一个名为
DatabaseManager.php
的文件,并在其中包含以下内容:
<?php class DatabaseManager { private $host = "localhost"; private $username = "your_username"; private $password = "your_password"; private $database = "your_database"; public function __construct() { $this->connect(); } private function connect() { $conn = new mysqli($this->host, $this->username, $this->password, $this->database); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $this->conn = $conn; } public function query($sql) { return $this->conn->query($sql); } public function escape_string($string) { return $this->conn->real_escape_string($string); } public function insert($table, $data) { $keys = implode(',', array_keys($data)); $values = ':' . implode(', :', array_keys($data)); $sql = "INSERT INTO {$table} ({$keys}) VALUES ({$values})"; $stmt = $this->conn->prepare($sql); foreach ($data as $key => $value) { $stmt->bindValue(":{$key}", $value); } return $stmt->execute(); } public function update($table, $data, $condition) { $keys = array_keys($data); $keys = ':' . implode(', :', $keys); $sql = "UPDATE {$table} SET {$keys} WHERE {$condition}"; $stmt = $this->conn->prepare($sql); foreach ($data as $key => $value) { $stmt->bindValue(":{$key}", $value); } return $stmt->execute(); } public function delete($table, $condition) { $sql = "DELETE FROM {$table} WHERE {$condition}"; return $this->query($sql); } public function select($table, $condition = [], $order_by = null, $limit = null) { $sql = "SELECT * FROM {$table} WHERE 1=1"; if (!empty($condition)) { $sql .= " AND {$condition}"; } if ($order_by) { $sql .= " ORDER BY {$order_by}"; } if ($limit) { $sql .= " LIMIT {$limit}"; } return $this->query($sql); } public function close() { $this->conn->close(); } } ?>
- 在你的主文件中(例如
index.php
),包含DatabaseManager.php
文件并使用它:
<?php require_once 'DatabaseManager.php'; $db = new DatabaseManager(); // 插入数据 $data = [ 'name' => 'John Doe', 'email' => 'john@example.com', 'age' => 30 ]; $db->insert('users', $data); // 查询数据 $results = $db->select('users', ['id' => 1]); foreach ($results as $row) { echo "ID: " . $row['id'] . ", Name: " . $row['name'] . ", Email: " . $row['email'] . "<br>"; } // 更新数据 $data = [ 'name' => 'Jane Doe', 'email' => 'jane@example.com' ]; $condition = ['id' => 1]; $db->update('users', $data, $condition); // 删除数据 $condition = ['id' => 1]; $db->delete('users', $condition); // 关闭数据库连接 $db->close(); ?>
这个DatabaseManager
类提供了基本的数据库操作,你可以根据需要扩展它以满足你的需求。