<?php
class Database {
private $host = 'localhost';
private $dbname = 'your_database_name';
private $username = 'your_username';
private $password = 'your_password';
private $conn;
public function __construct() {
// 创建数据库连接
$this->conn = new mysqli($this->host, $this->username, $this->password, $this->dbname);
// 检查连接
if ($this->conn->connect_error) {
die("连接失败: " . $this->conn->connect_error);
}
echo "连接成功";
}
// 查询数据库
public function query($sql) {
$result = $this->conn->query($sql);
if ($result) {
return $result;
} else {
die("查询失败: " . $this->conn->error);
}
}
// 预处理语句(更安全)
public function prepare($sql, $types = "", &$bind_params = array()) {
$stmt = $this->conn->prepare($sql);
if ($stmt) {
$types = str_repeat('s', count($bind_params));
$stmt->bind_param($types, ...$bind_params);
return $stmt;
} else {
die("预处理失败: " . $this->conn->error);
}
}
// 关闭数据库连接
public function close() {
$this->conn->close();
}
}
// 使用示例
$db = new Database();
$result = $db->query("SELECT * FROM your_table");
if ($result) {
while ($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
}
// 使用预处理语句
$stmt = $db->prepare("INSERT INTO your_table (name, email) VALUES (?, ?)", "ss", array('John Doe', 'john.doe@example.com'));
if ($stmt->execute()) {
echo "新记录插入成功";
}
$db->close();
?>
这段代码定义了一个简单的`Database`类,用于操作MySQL数据库。它包括了数据库连接、查询、预处理语句以及关闭连接的基本功能。使用时,你可以根据需要修改数据库连接信息,并使用类的方法执行SQL查询或预处理语句。注意,为了安全起见,建议使用预处理语句来防止SQL注入攻击。