PHP处理多表查询时的SQL语句拆分与重新组装

在自己写框架时候会发现,多表查询组装SQL语句
<?php $pre = "pre_"; $aid = "44"; $data = array("user.username,comment.uid,article.aid","user,comment,article","user.uid=comment.uid AND article.aid=comment.aid AND comment.aid=$aid"); //字段判断 if($data["0"] === "*"){ $filed = "*"; }else{ $arr = explode(",",$data["0"]); $length = count($arr); for($i=0; $i<$length; $i++){ $filed .= $pre.$arr[$i].","; } $filed = substr($filed, 0,-1); } //表名判断 if(strpos($data["1"],",") > 1){ $arr = explode(",",$data["1"]); $length = count($arr); for($i=0; $i<$length; $i++){ $table .= $pre.$arr[$i].","; } $table = substr($table, 0,-1); }else{ $table = $pre.$data["1"]; } //条件判断 $one = explode(" AND ", $data["2"]); $len1 = count($one); for($i=0; $i<$len1; $i++){ $two[] = explode("=", $one[$i]); } $len2 = count($two); for($i=0; $i<$len2; $i++){ for($j=0; $j<$len2-1; $j++){ if(strpos($two[$i][$j],".") > 1){ $where .= $pre.$two[$i][$j]."="; }else{ $where .= $two[$i][$j]; } } } $where = explode("=",$where); $len3 = count($where); for($i=0; $i<$len3; $i++){ if($i%2 == 0){ $c .=$where[$i]."="; }else{ $c .=$where[$i]." AND "; } } $where = substr($c, 0,-4); echo $query = "SELECT $filed FROM $table WHERE $where"; ?>

  

posted @ 2014-03-23 20:29  陈朔  阅读(814)  评论(0编辑  收藏  举报