PHP基于MySQLI函数封装的数据库连接工具类【定义与用法】
(编辑:jimmy 日期: 2025/10/29 浏览:3 次 )
本文实例讲述了PHP基于MySQLI函数封装的数据库连接工具类。分享给大家供大家参考,具体如下:
mysql.class.php:
<"SELECT * FROM {$table}";
if (!empty($field)) {
$field = '`' . implode('`,`', $field) . '`';
$sql = str_replace('*', $field, $sql);
}
if (!empty($where)) {
$sql = $sql . ' WHERE ' . $where;
}
$this->result = $this->mysqli->query($sql);
return $this->result->num_rows;
}
/**
* @return mixed 获取全部结果
*/
public function fetchAll()
{
return $this->result->fetch_all(MYSQLI_ASSOC);
}
/**
* 插入数据
* @param $table 数据表
* @param $data 数据数组
* @return mixed 插入ID
*/
public function insert($table, $data)
{
foreach ($data as $key => $value) {
$data[$key] = $this->mysqli->real_escape_string($value);
}
$keys = '`' . implode('`,`', array_keys($data)) . '`';
$values = '\'' . implode("','", array_values($data)) . '\'';
$sql = "INSERT INTO {$table}( {$keys} )VALUES( {$values} )";
$this->mysqli->query($sql);
return $this->mysqli->insert_id;
}
/**
* 更新数据
* @param $table 数据表
* @param $data 数据数组
* @param $where 过滤条件
* @return mixed 受影响记录
*/
public function update($table, $data, $where)
{
foreach ($data as $key => $value) {
$data[$key] = $this->mysqli->real_escape_string($value);
}
$sets = array();
foreach ($data as $key => $value) {
$kstr = '`' . $key . '`';
$vstr = '\'' . $value . '\'';
array_push($sets, $kstr . '=' . $vstr);
}
$kav = implode(',', $sets);
$sql = "UPDATE {$table} SET {$kav} WHERE {$where}";
$this->mysqli->query($sql);
return $this->mysqli->affected_rows;
}
/**
* 删除数据
* @param $table 数据表
* @param $where 过滤条件
* @return mixed 受影响记录
*/
public function delete($table, $where)
{
$sql = "DELETE FROM {$table} WHERE {$where}";
$this->mysqli->query($sql);
return $this->mysqli->affected_rows;
}
}
使用方法
<"_blank" href="https://www.jb51.net/Special/768.htm">php+mysqli数据库程序设计技巧总结》、《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》希望本文所述对大家PHP程序设计有所帮助。
下一篇:如何修改Laravel中url()函数生成URL的根地址