你可以给我提供一个php7.0 操作MySQL数据库的类吗? 必须包含,插入数据,查询数据,删除数据,更新数据。
时间: 2023-10-06 08:11:38 浏览: 98
当然可以,以下是一个简单的 PHP7.0 操作 MySQL 数据库的类,包含插入数据、查询数据、删除数据、更新数据的方法:
```php
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->connection = mysqli_connect($this->host, $this->username, $this->password, $this->database);
if (!$this->connection) {
die("Connection failed: " . mysqli_connect_error());
}
}
public function insert($table, $data) {
$keys = array_keys($data);
$values = array_values($data);
$query = "INSERT INTO $table (" . implode(", ", $keys) . ") VALUES ('" . implode("', '", $values) . "')";
return mysqli_query($this->connection, $query);
}
public function select($table, $conditions = []) {
$query = "SELECT * FROM $table";
if (!empty($conditions)) {
$query .= " WHERE ";
$i = 0;
foreach ($conditions as $key => $value) {
$query .= "$key='$value'";
if ($i < count($conditions) - 1) {
$query .= " AND ";
}
$i++;
}
}
$result = mysqli_query($this->connection, $query);
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
mysqli_free_result($result);
return $rows;
}
public function delete($table, $conditions) {
$query = "DELETE FROM $table WHERE ";
$i = 0;
foreach ($conditions as $key => $value) {
$query .= "$key='$value'";
if ($i < count($conditions) - 1) {
$query .= " AND ";
}
$i++;
}
return mysqli_query($this->connection, $query);
}
public function update($table, $data, $conditions) {
$query = "UPDATE $table SET ";
$i = 0;
foreach ($data as $key => $value) {
$query .= "$key='$value'";
if ($i < count($data) - 1) {
$query .= ", ";
}
$i++;
}
$query .= " WHERE ";
$i = 0;
foreach ($conditions as $key => $value) {
$query .= "$key='$value'";
if ($i < count($conditions) - 1) {
$query .= " AND ";
}
$i++;
}
return mysqli_query($this->connection, $query);
}
public function __destruct() {
mysqli_close($this->connection);
}
}
```
使用方法如下:
```php
$db = new MySQL("localhost", "username", "password", "database");
$data = ["name" => "John", "age" => 30, "email" => "john@example.com"];
$db->insert("users", $data);
$conditions = ["age" => 30, "email" => "john@example.com"];
$users = $db->select("users", $conditions);
$conditions = ["name" => "John"];
$db->delete("users", $conditions);
$data = ["age" => 31];
$conditions = ["name" => "John"];
$db->update("users", $data, $conditions);
```
以上代码是一个简单的实现,实际使用中需要考虑更多的安全和性能方面的问题。
阅读全文