<?php
/***********************************************本类功能说明*************************************
* 可用于管理后台的站内条件搜索等数据调取应用场景
*************************************************************************************************/
class SqlAdapter
{
/*
*@param array $data 传入的Sql语句条件数组
*
*
*数据表名
*$table='user' 说明:从数据表user中查询数据
*
*单一判断条件情况下
*$data['array1']=['param1>0'] 说明:把数据表'param1'字段中大于0的数据存为array1数组
*
*
*多个判断条件情况下
*$data['array2']=['param2=小明','or','param2=小刚'] 说明:把数据表'param2'字段中等于'小明'或'小刚'的数据存为array2数组
*$data['array3']=['param3>5','and','param3<9'] 说明:把数据表'param3'字段中大于5并且小于9的数据存为array3数组
*$data['array4']=['param4','like','%test%'] 说明:把数据表'param4'字段中模糊匹配test的数据存为array4数组
*
*查询字段
*$field=['id','name','grade'] 说明:查询id,name,grade字段
*
*
*联表查询
*$theJoin=['LEFT JOIN','user','userId=user.id'] 说明:$table左连接user数据表,以$table.userId=user.id为联表条件
*所生成的Sql语句示例:select * from $table left join user on $table.userId=user.id
*/
public function __construct($table='',$field=[],$data=[],$theJoin=[])
{
$this->table=$table;
$this->field=$field;
$this->data=$data;
$this->theJoin=$theJoin;
$this->sql='';
}
//根据传入参数拼接Sql字符串
public function CreateSql()
{
$sql_arr=[];
$this->sql='select ';
//初步拼接Sql语句,确定要查询的字段
if(count($this->field)>0){
//若传入的查询字段不为空
foreach($this->field as $value){
$this->sql.="{$value},";
}
$this->sql=rtrim($this->sql,',');
}else{
//若传入的查询字段为空,默认查询所有字段
$this->sql.='*';
}
//第二次拼接Sql字符串,加上数据表名$table
if($this->table!=''){
$this->sql.=" from {$this->table} ";
}else{
return '';
}
//第三次拼接Sql字符串,加上连接的数据表名
if(count($this->theJoin)>0){
foreach($this->theJoin as $key=>$value){
if($key==2){
$this->sql.="on {$this->table}.{$value} ";
}else{
$this->sql.="{$value} ";
}
}
}
//第四次拼接Sql字符串,加上包含查询条件的where从句
if(count($this->data)>0){
$this->sql.='where ';
//若传入的查询条件不为空
foreach($this->data as $key=>$value){
$sql=$this->sql;
foreach($value as $item){
$sql.="{$item} ";
}
$sql=rtrim($sql,' ');
$sql_arr[$key]=$sql;
}
}else{
$sql.='';
}
return $sql_arr;
}
}
一个简化MySQL数据库查询的PHP类
最新推荐文章于 2021-03-10 14:30:39 发布