MySQL是一种常用的关系型数据库管理系统,可以通过PHP来操作MySQL数据库。下面是一个简单的PHP工具类,包含了MySQL的增删改查操作。
class MySQL {
private $host;
private $username;
private $password;
private $database;
private $connection;
public function __construct($host, $username, $password, $database) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->connect();
}
private function connect() {
$this->connection = mysqli_connect($this->host, $this->username, $this->password, $this->database);
if (!$this->connection) {
die("连接数据库失败:" . mysqli_connect_error());
}
}
public function query($sql) {
$result = mysqli_query($this->connection, $sql);
if (!$result) {
die("查询失败:" . mysqli_error($this->connection));
}
return $result;
}
public function insert($table, $data) {
$columns = implode(", ", array_keys($data));
$values = "'" . implode("', '", array_values($data)) . "'";
$sql = "INSERT INTO $table ($columns) VALUES ($values)";
return $this->query($sql);
}
public function update($table, $data, $condition) {
$set = "";
foreach ($data as $key => $value) {
$set .= "$key = '$value', ";
}
$set = rtrim($set, ", ");
$sql = "UPDATE $table SET $set WHERE $condition";
return $this->query($sql);
}
public function delete($table, $condition) {
$sql = "DELETE FROM $table WHERE $condition";
return $this->query($sql);
}
public function select($table, $condition = "") {
$sql = "SELECT * FROM $table";
if (!empty($condition)) {
$sql .= " WHERE $condition";
}
$result = $this->query($sql);
$data = [];
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
return $data;
}
public function close() {
mysqli_close($this->connection);
}
}
使用示例:
$host = "localhost";
$username = "root";
$password = "password";
$database = "mydatabase";
$mysql = new MySQL($host, $username, $password, $database);
// 插入数据
$data = [
"name" => "John",
"age" => 25,
"email" => "john@example.com"
];
$mysql->insert("users", $data);
// 更新数据
$data = [
"age" => 26,
"email" => "john@example.com"
];
$mysql->update("users", $data, "name = 'John'");
// 删除数据
$mysql->delete("users", "name = 'John'");
// 查询数据
$users = $mysql->select("users");
print_r($users);
$mysql->close();
请注意,这只是一个简单的示例,实际使用中可能需要根据具体需求进行修改和扩展。
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站