网站首页 mysql技术
mysql连贯操作
发布时间:2016-05-30 09:06查看次数:5471
mysql连贯操作
记录下思路! 首先使用到魔术方法
用数组把要使用到的命令都存在数组中~
CALL 的时间判断执行的命令有没有在数组中!如果有 他的参数就是当前数组键的值
就这么简单~!!连贯操作
最后用一个get命令来生成SQL
没有返回数据哦!也可以取了数据在返回回来!
class user
{
protected $table = 'user';
protected $sql = array(
'select' => '*',
'where' => '',
'group' => '',
'order' => '',
'limit' => '',
'having' => '',
);
/**
* 连贯操作时,调用field() where() order() limit() group() having()方法且组合成sql语句
* 此方法为PHP魔术方法,调用类中不存在的方法时就会自动调用此方法
* @param $methodName 调用不存在的方法时,接收这个方法名称的字符串
* @param $args 调用不存在的方法时,接收这个方法的参数,以数组形式接收
*/
public function __call($methodName, $args)
{
//把要请求的方法名,统一转为小写
$methodName = strtolower($methodName);
//若请求方法名与成员属性数组$sql下标对应上;则将第二个参数,赋值给数组中"下标对应的元素"
if (isset($this->sql[$methodName])) {
$this->sql[$methodName] = $args;
} else {
echo '调用类' . get_class($this) . '中的' . $methodName . '()方法不存在';
}
//返回对象;从而可以继续调用本对象中的方法,形成连贯操作
return $this;
}
public function getArrayLevel($arr){
$al = array(0);
function aL($arr,&$al,$level=0){
if(is_array($arr)){
$level++;
$al[] = $level;
foreach($arr as $v){
aL($v,$al,$level);
}
}
}
aL($arr,$al);
return max($al);
}
/**
* 用此方法拼接成一个select的sql语句;[PS:此方法终结了连贯操作,置于连贯操作的最后面]
*/
public function get()
{
//优化判断如果数据是数组 转换成字符串
if (is_array($this->sql['select'])) {
$this->sql['select'] = implode(',', $this->sql['select']);
}
//优化判断如果数据是数组 转换成字符串
if (is_array($this->sql['where'])) {
if($this->getArrayLevel($this->sql['where'])>1){
$tmp = $this->sql['where'][0];
$tmp2='';
foreach ($tmp as $k => $v) {
$tmp2 .= "'$k'" .'='."'$v'".',';
}
$tmp2 = trim($tmp2,',');
$this->sql['where'] = $tmp2;
}else{
$tmp = $this->sql['where'];
$this->sql['where'] = implode('=\'', $this->sql['where'])."'";
}
}
if (is_array($this->sql['order'])) {
$this->sql['order'] = implode(',\'', $this->sql['order'])."'";
}
if (is_array($this->sql['limit'])) {
$this->sql['limit'] = implode(',', $this->sql['limit']);
}
$sql = '';
//循环拼接SQL语句
foreach ($this->sql as $k =>$v){
//拼接select
if($k == 'select'){
$sql .= 'select '. $v .' '. $this->table;
}
//拼接where
if($k == 'where'){
$sql .= ' where '. $v ;
}
//拼接order
if($k == 'order'){
$sql .= ' order '. $v .' ';
}
//拼接limit
if ($k == 'limit' && $v !=''){
$sql .= 'limit '.$v;
}
}
//按照select语法拼接sql字符串[PS:可以在mysql命令行中执行"help select;"查看其语法构结]
// $sql = "SELECT {$this->sql['select']} FROM {$this->table} where 1 AND {$this->sql['where']} {$this->sql['group']} {$this->sql['having']} {$this->sql['order']} limit {$this->sql['limit']}";
echo $sql;
}
}关键字词:mysql连贯操作