用PHP写一个 mysql数据库增删改查的全能类文件 和 使用示例
时间: 2024-03-06 14:51:56 浏览: 86
好的,下面是一个基本的 MySQL 数据库增删改查全能类的示例代码:
```php
class MySQLDB {
private $host;
private $username;
private $password;
private $database;
private $conn;
public function __construct($host, $username, $password, $database) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->connect();
}
public function connect() {
$this->conn = mysqli_connect($this->host, $this->username, $this->password, $this->database);
if (!$this->conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
public function query($sql) {
$result = mysqli_query($this->conn, $sql);
if (!$result) {
die("Query failed: " . mysqli_error($this->conn));
}
return $result;
}
public function select($table, $columns = "*", $where = "") {
$sql = "SELECT $columns FROM $table";
if ($where != "") {
$sql .= " WHERE $where";
}
return $this->query($sql);
}
public function insert($table, $data) {
$columns = "";
$values = "";
foreach ($data as $column => $value) {
$columns .= "$column,";
$values .= "'$value',";
}
$columns = rtrim($columns, ",");
$values = rtrim($values, ",");
$sql = "INSERT INTO $table ($columns) VALUES ($values)";
return $this->query($sql);
}
public function update($table, $data, $where = "") {
$sql = "UPDATE $table SET ";
foreach ($data as $column => $value) {
$sql .= "$column='$value',";
}
$sql = rtrim($sql, ",");
if ($where != "") {
$sql .= " WHERE $where";
}
return $this->query($sql);
}
public function delete($table, $where = "") {
$sql = "DELETE FROM $table";
if ($where != "") {
$sql .= " WHERE $where";
}
return $this->query($sql);
}
public function close() {
mysqli_close($this->conn);
}
}
```
这个类包含了连接数据库、执行 SQL 查询、插入数据、更新数据、删除数据和关闭连接的基本操作。使用示例代码如下:
```php
$db = new MySQLDB("localhost", "root", "password", "mydatabase");
// 查询
$result = $db->select("mytable", "*", "id=1");
while ($row = mysqli_fetch_assoc($result)) {
echo $row["column1"] . " " . $row["column2"] . "<br>";
}
// 插入
$data = array("column1" => "value1", "column2" => "value2");
$db->insert("mytable", $data);
// 更新
$data = array("column1" => "newvalue1", "column2" => "newvalue2");
$db->update("mytable", $data, "id=1");
// 删除
$db->delete("mytable", "id=1");
$db->close();
```
以上代码用于连接名为 `mydatabase` 的 MySQL 数据库,并执行查询、插入、更新和删除操作,最后关闭连接。您可以根据自己的需求修改这个类和使用示例代码。
阅读全文