要通過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
類提供了基本的數據庫操作,你可以根據需要擴展它以滿足你的需求。