pdo 封装增删改查类
<?php
/**
* Class model
* @package Core\lib
*/
class model
{
protected $pdo = null; // 连接数据库
protected $table = null; // 表名
protected $where = null; // where 条件
protected $order = null; // order 条件
protected $limit = null; // limit
protected $like = ''; // 包含 条件
protected $field = '*'; // 要查询的 条件
/**
* model constructor.
* @param $table
* pdo连接数据库
*/
public function __construct($table)
{
$database = conf::all('database');
$this->table = $table;
try{
$this->pdo = new PDO($database['DSN'], $database['USERNAME'], $database['PASSWD']);
$this->pdo->query('set names utf8');
}catch(\PDOException $e){
p($e->getMessage());
}
}
/**
* @return array
* 查询所有
*/
public function select()
{
$stmt = $this->pdo->prepare("select ".trim($this->field)." from ".$this->table." ".$this->where." ".$this->order." ".$this->limit."");
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $data;
}
/**
* @return mixed
* 单条查询
*/
public function first()
{
$sql = "select ".$this->field." from ".$this->table." ".$this->where." limit 1";
$res = $this->pdo->query($sql);
$res->setFetchMode(PDO::FETCH_ASSOC); //数字索引方式
$row = $res->fetch();
return $row;
}
/**
* @param $data
* @return $this
* 添加
*/
public function insert($data)
{
if(is_array($data)){
$val = array_values($data);
$str = '';
$key = array_keys($data);
$keys = implode(',',$key);
foreach($key as $k=>$v){
$str.=":$v".',';
}
$str = rtrim($str,',');
$stmt=$this->pdo->prepare("insert into ".$this->table."($keys) values($str)");
$arr = [];
foreach($key as $k=>$v){
$arr[':'.$v] = $val[$k];
}
$stmt->execute($arr);
// $this->pdo->lastInsertId();
return $this;
}
}
/**
* @param $data
* @return $this
* 更新 修改
*/
public function update($data)
{
$str = '';
foreach($data as $k=>$v){
$str.=$k.'='.':'.$k.',';
}
$str = rtrim($str,',');
$stmt = $this->pdo->prepare("update ".$this->table." set ".$str." ".$this->where);
$arr = [];
foreach($data as $k=>$v){
$arr[':'.$k] = $v;
}
if($stmt->execute($arr))
{
return $this;
// echo "最后插入的ID:".$this->pdo->lastInsertId();
}else{
echo "执行失败";
}
}
/**
* @return $this
* 删除
*/
public function delete()
{
$sql="delete from ".$this->table." ".$this->where;
$res = $this->pdo->exec($sql);
return $res;
}
/**
* @param $data
* @return $this
* 查询字段
*/
public function field($field)
{
$this->field = is_array( $field ) ? '`' . implode( '`,`', $field ) . '`' : $field;
return $this;
}
/**
* @param $option
* @return $this
* where 条件
*/
public function where($option)
{
$this->where = 'where ';
$and = 'and';
if(is_string($option)){
$this->where.= $option;
}elseif(is_array($option)){
foreach($option as $k=>$v){
$for = $k.'='.$v;
$res = $this->where.= isset($mark) ? ' '.$and.' '.$for : $for;
$mark = 1;
}
}
return $this;
}
/**
* @param $option
* @return $this
* 排序
*/
public function order($option)
{
$this->order = 'order by ';
if(is_string($option)){
$this->order.= $option;
}
return $this;
}
/**
* @param $page
* @param null $pageSize
* @return $this
* 限制条数
*/
public function limit($page,$pageSize = null)
{
if($pageSize == null){
$this->limit = 'limit '.$page;
}else{
$pageval = intval($page-1) * $pageSize;
$this->limit = "limit ".$page.",".$pageval ;
}
return $this;
}
/**
* 字段和表名添加 `符号
* 保证指令中使用关键字不出错 针对mysql
* @param string $value
* @return string
*/
protected function _addChar($value)
{
if ('*'==$value || false!==strpos($value,'(') || false!==strpos($value,'.') || false!==strpos($value,'`')) {
//如果包含* 或者 使用了sql方法 则不作处理
} elseif (false === strpos($value,'`') ) {
$value = '`'.trim($value).'`';
}
return $value;
}
/**
* 过滤并格式化数据表字段
* @param string $tbName 数据表名
* @param array $data POST提交数据
* @return array $newdata
*/
protected function _dataFormat($tbName,$data)
{
if (!is_array($data)) return array();
$table_column = $this->_tbFields($tbName);
$ret=array();
foreach ($data as $key=>$val) {
if (!is_scalar($val)) continue; //值不是标量则跳过
if (array_key_exists($key,$table_column)) {
$key = $this->_addChar($key);
if (is_int($val)) {
$val = intval($val);
} elseif (is_float($val)) {
$val = floatval($val);
} elseif (preg_match('/^\(\w*(\+|\-|\*|\/)?\w*\)$/i', $val)) {
// 支持在字段的值里面直接使用其它字段 ,例如 (score+1) (name) 必须包含括号
$val = $val;
} elseif (is_string($val)) {
$val = '"'.addslashes($val).'"';
}
$ret[$key] = $val;
}
}
return $ret;
}
/**
* 取得数据表的字段信息
* @param string $tbName 表名
* @return array
*/
protected function _tbFields($tbName)
{
$sql = 'SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME="'.$tbName.'" AND TABLE_SCHEMA="'.$this->_dbName.'"';
$stmt = self::$_dbh->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$ret = array();
foreach ($result as $key=>$value) {
$ret[$value['COLUMN_NAME']] = 1;
}
return $ret;
}
}