上代码
<?php
class MySQL {
private $host;
private $username;
private $password;
private $database;
private $conn;
function __construct($host, $username, $password, $database) {
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $database;
$this->conn = mysqli_connect($host, $username, $password, $database);
if(mysqli_connect_errno()) {
throw new Exception(mysqli_connect_error());
}
}
// 查询操作
public function query($sql) {
$result = mysqli_query($this->conn, $sql);
if(!$result) {
throw new Exception(mysqli_error($this->conn));
} else {
return $result;
}
}
// 获取单条记录
public function getOne($sql) {
$result = $this->query($sql);
$row = mysqli_fetch_assoc($result);
return $row;
}
// 获取多条记录
public function getAll($sql) {
$result = $this->query($sql);
$rows = array();
while($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
}
// 插入操作
public function insert($table, $data) {
$keys = array();
$values = array();
foreach($data as $key => $value) {
$keys[] = "`{$key}`";
$values[] = "'{$value}'";
}
$keys_str = implode(",", $keys);
$values_str = implode(",", $values);
$sql = "INSERT INTO `{$table}` ({$keys_str}) VALUES ({$values_str})";
$this->query($sql);
return $this->getInsertId();
}
// 获取刚插入的自增主键ID
public function getInsertId() {
return mysqli_insert_id($this->conn);
}
// 更新操作
public function update($table, $data, $where = '') {
$set = array();
foreach($data as $key => $value) {
$set[] = "`{$key}`='{$value}'";
}
$set_str = implode(",", $set);
$where_str = empty($where) ? '' : " WHERE {$where}";
$sql = "UPDATE {$table} SET {$set_str}{$where_str}";
$this->query($sql);
return $this->affectedRows();
}
// 删除操作
public function delete($table, $where) {
$where_str = empty($where) ? '' : " WHERE {$where}";
$sql = "DELETE FROM {$table}{$where_str}";
$this->query($sql);
return $this->affectedRows();
}
// 受影响行数
public function affectedRows() {
return mysqli_affected_rows($this->conn);
}
// 释放连接资源
public function __destruct() {
mysqli_close($this->conn);
}
}
//使用示例
//连接Mysql
$db = new MySQL('localhost', 'username', 'password', 'database');
// 查询操作
$result = $db->query("SELECT * FROM `users`");
// 获取单条记录
$row = $db->getOne("SELECT * FROM `users` WHERE `id`=1");
// 获取多条记录
$rows = $db->getAll("SELECT * FROM `users` WHERE `age`>19");
// 插入操作
$last_insert_id = $db->insert("users", array("name" => "tom", "age" => 20, "gender" => "1"));
// 更新操作
$affected_rows = $db->update("users", array("age" => 22), "`name`='tom'");
// 删除操作
$affected_rows = $db->delete("users", "`age`<19");