增删改查,删除就不写了,一般都是软删除,可以合并到update中
<?php
class db {
public $connect;
public function __construct() {
try {
$host = '127.0.0.1';
$user = 'root';
$password = 'root';
$database = 'test';
$this->connect = mysqli_connect($host, $user,$password);
if (empty($this->connect)) {
die('数据库配置错误');
}
if (!mysqli_select_db($this->connect, $database)) {
die('数据库错误');
}
mysqli_query($this->connect,"set names utf8;");
} catch (Exception $e) {
die($e->getMessage() . $e->getFile() . $e->getLine());
}
}
public function __destruct() {
mysqli_close($this->connect);
}
/**
* 判断数据表是否存在
* @param $table
* @return bool
*/
public function isTableExist($table)
{
$sql = "show tables";
$result = mysqli_query($this->connect, $sql);
$data = [];
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$row = array_values($row);
$data[] = $row[0];
}
if (empty($data)) {
return false;
}
if (!in_array($table, $data)) {
return false;
}
return true;
}
/**
* 插入数据库
*/
public function add ($table, $insertData) {
if (!empty($table) && count($insertData) > 0) {
$column = '';
$insertValue = '';
foreach ($insertData as $key => $value) {
$column .= ',`' . $key . '`';
$insertValue .= ",'" . $value . "'";
}
$sql = 'insert into ' . $table . ' ( ' . trim($column, ',') . ') values (' . trim($insertValue, ',') . ')';
mysqli_query($this->connect, $sql);
return mysqli_insert_id($this->connect);
}
return 0;
}
/**
* 修改数据
* @param string $table 表名
* @param array $condition 更新条件
* @param array $updateData 更新数据
* @return bool|mysqli_result
*/
public function update (string $table, array $condition, array $updateData) {
if (!self::isTableExist($table)) {
return false;
}
if (empty($condition) || empty($updateData)) {
return false;
}
$sql = "update `$table` set ";
$updateArr = [];
foreach ($updateData as $key => $value) {
$updateArr[] = " `$key` = '$value' ";
}
$sql .= implode(',', $updateArr);
$whereArr = [];
foreach ($condition as $key => $value) {
$whereArr[] = " `$key` = '$value' ";
}
$sql .= " where " . implode(' and ', $whereArr);
return mysqli_query($this->connect, $sql);
}
/**
* 查询数据
* @param string $table 数据表
* @param array $field 要查询的字段
* @param array $where 查询条件
* @return array
*/
public function select(string $table, array $field = ['*'], array $where = []) {
if (mysqli_query($this->connect, $table)) {
return [];
}
if (in_array('*', $field)) {
$fields = '*';
} else {
$fields = implode(',', $field);
}
$sql = "select $fields from `$table`";
if (!empty($where)) {
$whereArr = [];
foreach ($where as $key => $value) {
$whereArr[] = " `$key` = '$value' ";
}
$sql .= " where " . implode(' and ', $whereArr);
}
$result = mysqli_query($this->connect, $sql);
if (empty($result)) {
return [];
}
$data = [];
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[]= $row;
}
return $data;
}
}