《php使用pdo方式操作mysql类》由会员分享,可在线阅读,更多相关《php使用pdo方式操作mysql类(9页珍藏版)》请在金锄头文库上搜索。
1、pdo = new PDO($dsn, $user, $pass); /初始化一个PDO对象$this-pdo-query(set names utf8);/* * 查询数据自带分页判断 * param string $table * param array(key=value)|string $where * param array(key=value) $order 排序方式传入d或者a,d=desc,a=asc * param array(page=1,pagesize=20)|null $pageing * return array(rows=rows,data=data) */pub
2、lic function Select($table,$where,$order=null,$pageing=null)$list = array();$sql = ;/组合查询条件if ($where != null) if (is_array($where) $sql .= where ;$i = 1;foreach ($where as $key=$value)if (is_array($value) /指定匹配方式switch ($value0)case in:$sql .= $key in (:$key);break;default:$sql .= $key .$value0. :$
3、key;break;else/不指定匹配方式,默认使用等于$sql .= $key = :$key;/未结束,条件用,分隔if ($i $value)if ($value = d)$value = desc;else $value = asc;$sql .= $key $value;if ($i pdo-prepare($rowsql);/绑定参数结果foreach ($where as $key=$value)if (is_array($value) if ($value0 = like) $stmt-bindValue(:$key, %.$value1.%);else$stmt-bindV
4、alue(:$key, $value1);else$stmt-bindValue(:$key, $value);$stmt-execute();foreach ($stmt as $item)$rows = $itemcount;break;/组合完整sql语句$sql = SELECT * FROM $table .$sql;/判断分页if ($pageing != null) $sql .= limit .($pageingpage - 1)*$pageingpagesize).,.$pageingpagesize;/预处理sql语句$sth = $this-pdo-prepare($sq
5、l);$sth-setFetchMode(PDO:FETCH_ASSOC);/绑定参数结果foreach ($where as $key=$value)if (is_array($value) if ($value0 = like) $sth-bindValue(:$key, %.$value1.%);else$sth-bindValue(:$key, $value1);else$sth-bindValue(:$key, $value);/取得结果$sth-execute();/将结果集转为array$list = $sth-fetchAll();/将结果转为array/* foreach (
6、$sth as $row)$list = $row; */return array(rows=$rows,data=$list);/* * 为EasyUI提供JSON格式数据返回结果 */public function JsonSelect($table, $where,$order,$pageing)$data = $this-Select($table, $where,$order,$pageing);return array(total=$datarows,rows=$datadata);/* * 获取单条信息 * param unknown $table * param unknown
7、 $where * param unknown $order */public function Single($table,$where,$order=null)$list = $this-Select($table, $where, $order, null);$data = $listdata;if ($data != null) return $data0;elsereturn null;/* * 写入数据库 * param unknown $table * param unknown $fields */public function Insert($table,$fields)$s
8、ql = insert into $table ;/组合字段$sql .= (;$i=1;foreach ($fields as $key=$value)$sql .= $key;if ($i $value)$sql .= :$key;if ($i pdo-prepare($sql);/绑定参数结果foreach ($fields as $key=$value)$stmt-bindValue(:$key, $value);$result = $stmt-execute();return $result;/* * 更新数据库 * param unknown $table * param unknown $fields * param unknown $where */public function Update($table,$fields,$where)$sql = update $table set ;$i=1;foreach ($fields as $key=$value)$sql .= $key=:$key;if ($i $value)if (is_array($value) if (key($value) = in) $sql .= $key in (