<?php class Mysql{ //拼接sql语句 public function autoExecute($data='',$table,$mode = "insert",$where = "where 1 limit 1"){ //insert 和 update 语句需要传入数组判断 if(is_array($data)){ //Update语句的拼接 if($mode == "update"){ $sql="update $table set "; foreach($data as $key=>$val){ $sql.=$key ." = "."'$val'".','; } //循环后语句是$sql updata $table set filed1 = value1,filed2=value2,filed3=values3, $sql=substr(trim($sql),0,-1).' '.$where; //先将sql语句的首位空格去掉,然后将后面的','给去掉拼接$where条件 return $this->query($sql); } //insert 语句的拼接,默认是insert $sql = $mode . " into ".$table ." ( " . implode(',',array_keys($data)); $sql.=" ) value "."('".implode("','",array_values($data))."')"; return $this->query($sql); }else{ //delete 语句的拼接 //当语句为delete时候,此时$data传入是表名,$table传入的是delete $mode传入是where条件 if($table = 'delete'){ $sql="delete from ".$data.' '.$mode; $this->query($sql); return $this->affected_rows(); }else{ return false; } } } //query方法 public function query($sql){ $res = mysql_query($sql); return $res; } } //+++++++++++++++自动拼接sql语句使用方法+++++++++++++++++++// $mysql = new Mysql(); //insert 语句 $data=array( 'username'=>'demo', 'password'=>'admin' ); $mysql->autoExecute($data,'user表'); //updata 语句 $where = "where id > 10;"; $mysql->autoExecute($data,'user表','update',$where); //delete 语句 $mysql->autoExecute('user表','delete',$where);
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/database/4582.html