一.封装常用增删查改操作方法
<?php
class BaseDAO{
//创建数据
public function create($table_name,$model){
$columns_k='';
$columns_v='';
foreach($model as $key=>$value){
$columns_k=empty($columns_k)?
sprintf('`%s`',$key):
sprintf('%s,`%s`',$columns_k,$key);
$columns_v=empty($columns_v)?
sprintf("'%s'",$value):
sprintf("%s,'%s'",$columns_v,$value);
}
$sqlcmd=sprintf("INSERT INTO `%s`(%s) VALUES(%s)",$table_name,
$columns_k,$columns_v);
echo $sqlcmd;
}
//修改数据
public function modify($table_name,$model,$primary){
$columns='';
$wheres='';
foreach($model as $key=>$value){
$columns=empty($columns)?
sprintf("`%s`='%s'",$key,$value):
sprintf("%s,`%s`='%s'",$columns,$key,$value);
}
$wheres=sprintf("`%s`='%s'",$primary['pk'],$primary['pv']);
$sqlcmd=sprintf("UPDATE `%s` SET %s WHERE %s",$table_name,$columns,$wheres);
echo $sqlcmd;
}
//删除数据
public function remove($table_name,$model){
$wheres='';
foreach($model as $key=>$value){
$wheres=empty($wheres)?
sprintf("`%s`='%s'",$key,$value):
sprintf("%s and `%s`='%s'",$wheres,$key,$value);
}
$sqlcmd=sprintf("DELETE FORM `%s` WHERE %s",
$table_name,$wheres);
echo $sqlcmd;
}
//查询数据
public function select($table_name,$conditons){
$wheres='';
foreach($conditons as $key=>$value){
$wheres=empty($wheres)?
sprintf("`%s`='%s'",$key,$value):
sprintf("%s and `%s`='%s'",$wheres,$key,$value);
}
$sqlcmd=sprintf("SELECT * FROM `%s` WHERE %s",$table_name,$wheres);
echo $sqlcmd;
}
//根据主键查找数据
public function findById($table_name,$primary){
$sqlcmd=sprintf("SELECT * FROM `%s` WHERE `%s`='%s' LIMIT 1",$table_name,$primary['pk'],$primary['pv']);
echo $sqlcmd;
}
}
二.调用实例
<?php
require_once("./BaseDAO.class.php");
echo '<br/>增加<br/>';
BaseDAO::create('cb_admin',array('username'=>'admin','password'=>md5('pwd')));
echo '<br/>查询<br/>';
BaseDAO::select('cb_admin',array('username'=>'admin','password'=>md5('pwd')));
echo '<br/>修改<br/>';
BaseDAO::modify('cb_admin',array('username'=>'admin','password'=>md5('pwd')),array('pk'=>'id','pv'=>1));
echo '<br/>删除<br/>';
BaseDAO::remove('cb_admin',array('username'=>'admin','password'=>md5('pwd')));
echo '<br/>明细<br/>';
BaseDAO::findById('cb_admin',array('pk'=>'id','pv'=>1));