1、把字符串拼接为SQL(增删改查)语句;
2、运用循环和预处理,批量提交数据处理请求;
<?php //连接数据库 function con(){ $dsn = 'mysql:dbname=oa;host=127.0.0.1;charset=utf8;port=3306'; $user = 'root'; $psw = 'root'; try{ $p = new PDO($dsn,$user,$psw); echo '连接成功'; } catch(PDOException $e){ print_r($e->getMessage()); exit; } return $p; } //$conditions的参数[['列名','比较符号',比较值],[...]];此处只考虑WHERE子句只有一个条件或多个要求同时成立的条件;如果只有一个条件,请在一位数组外面套多一对中括号。 function delete($table, $conditions=[]){ $c = con(); $sql = 'DELETE FROM '.$table.' WHERE '; if(empty($conditions)){ echo '要指定删除条件'; return false; }else{ for($i=0;$i<count($conditions);$i++){ $bind[$i] = $conditions[$i][2]; $sql .= $conditions[$i][0].$conditions[$i][1].":c$i AND "; } $sql = rtrim(rtrim($sql),'AND'); } $a = $c->prepare($sql); for($i=0;$i<count($bind);$i++){ $a->bindParam(":c$i",$bind[$i]); } var_dump($a->execute()); $a = null; $c = null; } // delete('user',[['id','>','3']]); //$sets传参格式['列名'=>值,'列名'=>值];$where参数设置一样 function update($table,$sets=[],$wheres=[]){ $c = con(); $sql = 'UPDATE '.$table.' SET '; //拼接SQL语句的同时,建立提交数据库的关联数组 $data=[]; if(empty($sets)){ return '请输入列名'; }else{ foreach($sets as $k1=>$v1){ $sql .= $k1."=:$k1, "; $data[":$k1"] = $v1; } $sql = rtrim(rtrim($sql),','); } if(empty($wheres)){ return '请指定修改条件'; }else{ $sql .= " WHERE "; //因where子句中的":字段名"与前面SET字句的会有重复,要加一个where前缀区分,才能存进关联数组 foreach($wheres as $k2=>$v2){ $sql .= $k2."=:where$k2 AND "; $data[":where$k2"] = $v2; } $sql = rtrim(rtrim($sql),'AND'); } $a = $c->prepare($sql); $a->execute($data); $a = null; $c = null; } // update('user',['name'=>'MS','gender'=>3],['gender'=>1,'name'=>'xm']); function select($table,$fields=[],$where='',$order='',$limit=''){ $c = con(); $sql = 'SELECT '; if(empty($fields)){ $sql .="* "; }else{ foreach ($fields as $field) { $sql .= rtrim($field).","; } $sql = rtrim($sql,","); } $sql .= " FROM ".$table; if(!empty($where)){ $sql .= " WHERE ".$where; } if(!empty($order)){ $sql .= " ORDER BY ".$order; } if (!empty($limit)) { $sql .= ' LIMIT '.$limit; } $a = $c->prepare($sql); if($a->execute()){ if($a->rowCount()){ $a->setFetchMode(PDO::FETCH_ASSOC); $ret = $a->fetchAll(); return $ret; $a = null; $c = null; }else{ return '获取到0条数据'; } }else{ return '获取数据失败'; } } // var_dump(select('user',['name','gender'],'gender=100','department','5')); function insert($table,$cols=[],$data=[]){ $c = con(); //开始拼接SQL语句 $sql = "INSERT INTO ".$table." ("; $qmark = ""; foreach ($cols as $col) { $sql .= $col.","; $qmark .= "?,"; } $sql = rtrim($sql,','); $qmark = rtrim($qmark,','); $sql .= ") VALUES(".$qmark.")"; //预处理 $a = $c->prepare($sql); //进行绑定 for($i=1;$i<=count($cols);$i++){ $a->bindParam($i,$bind[$i]); } //如果数据是一维数组,转化为二维数组 if(count($data)==count($data,1)){ $data=[$data]; } //传值 for($j=0;$j<count($data);$j++){ for($i=1;$i<=count($cols);$i++){ $bind[$i]=$data[$j][$i-1]; } $a->execute(); $a = null; $c = null; } } // insert('user',$cols=['name','gender'],$data=['消化',3]);
总结:
1、写代码过程,要不断var_dump()检测是否有误,不要一堆代码了才检查;
2、要注销对象;
3、方法的参数要添加说明;
4、巧用双引号中变量会自动转化为值;