<?php
/**
* 数据库操作类,文件名:Db.class.php
*/
class Mysql
{
private $conn;//保存数据库连接资源
//构造方法:主要实现数据库连接,设置编码格式,并把数据库连接对象conn保存到属性中,为其他方法使用
function __construct( $host, $usr, $pwd, $dbname, $port = 3306, $coding = 'utf8')
{
//建议使用mysqli,连接mysql数据库
$conn = mysqli_connect($host, $usr, $pwd, $dbname, $port);
if (mysqli_connect_errno($conn)) {
echo "连接数据库失败: " . mysqli_connect_error();
}
// 设置数据库连接字符集
mysqli_set_charset($conn, $coding);
$this->conn = $conn;
}
//析构方法:不会有任何参数
function __destruct()
{
//关闭数据库连接,放在析构方法中最合适不过了
mysqli_close($this->conn);
echo "<br/>断开数据库连接";
}
/**
* @param $table 数据表名
* @param $data 添加的数据,关联数组类型 格式为:['no'=>'1001','name'=>'张三',]
*/
function add($table,$data){
if(!is_array($data)){
die('第二参数必须必须是关联数组');
}
$fields = $values = '';
//遍历$data,构建字段列表和值列表
foreach ($data as $k=>$v){
$fields .= '`' . $k . '`,';
$values .= '"' . $v . '",';
}
//去除末尾的逗号
$fields = rtrim($fields,',');
$values = rtrim($values,',');
//构建sql指令
$sql = "insert into {$table} ($fields) values ($values)";
$ret = mysqli_query($this->conn,$sql);
return $ret;
}
/**
* 更新记录
* @param $table 表名
* @param $data 数据, 数据类型:字符串、关联数组
* @param $where 更新条件,数据类型:关联数组
*/
function update($table, $data, $where = '1=1')
{
if (!is_array($data)) {
die('第二个参数必须是数组');
}
$values = '';
foreach ($data as $k => $v) {
$values .= "{$k}='{$v}',";
}
$values = rtrim($values, ',');
$condition = '';
if (is_array($where)) {
foreach ($where as $k => $v) {
$condition .= " {$k}='{$v}' and";
}
$condition = substr($condition, 0, -3);
} else {
$condition = $where;
}
$sql = "update {$table} set {$values} where {$condition}";
$ret = mysqli_query($this->conn,$sql);
return $ret;
}
/**
* 查询记录
* @param $table 表名
* @param array $where 查询条件,可以是字符串,也可以是数组
* @param string $fields 查询字段
* 返回二维数组
*/
function getAll($table,$where='1=1',$fields="*"){
$condition = '';
if(is_array($where)){
foreach ($where as $k=>$v){
$condition .= " {$k}='{$v}' and";
}
$condition = substr($condition, 0, -3);
}else{
$condition = $where;
}
$sql = "select {$fields} from {$table} where $condition";
$ret = mysqli_query($this->conn,$sql);
$arr =array();
while($row = mysqli_fetch_assoc($ret)){
$arr[] = $row;
}
return $arr;
}
/**
* 删除记录
* @param $table 表名
* @param array $where 查询条件,可以是字符串,也可以是数组
*/
function delete($table,$where){
$condition = '';
if(!empty($where)){
if(is_array($where)){
foreach ($where as $k=>$v){
$condition .= " {$k}='{$v}' and";
}
$condition = substr($condition, 0, -3);
}else{
$condition = $where;
}
}else{
echo '请输入查询语句'; exit;
}
$sql = "delete from {$table} where {$condition}";
$ret = mysqli_query($this->conn,$sql);
return $ret;
}
}
?>
PHP面向对象之数据库操作
最新推荐文章于 2024-07-10 18:43:48 发布