PHP数据库常用操作PDO(连接-新删改查) 常用函数操作封装类
//链接数据库 if(!function_exists('connect')){ function connect( $dbname,$type='mysql',$host='127.0.0.1', $charset='utf8', $port=3306,$user='root',$pass='root') { $dsn = "{$type}:host={$host}; dbname={$dbname}; charset={$charset}; port={$port}"; //配置连接属性 $option=[ PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE=>PDO::CASE_NATURAL, PDO::ATTR_EMULATE_PREPARES=>true, PDO::ATTR_PERSISTENT=>true, ]; try{ $pdo=new PDO($dsn,$user,$pass,$option); }catch(PDOException $e){ die('Connect ERROR:'.$e->getMessage()); } return $pdo; } } if(!function_exists('insert')){ function insert($pdo,$table,$data=[]) { //SQL语句 $sql = "INSERT IGNORE {$table} SET "; foreach (array_keys($data) as $field) { $sql .= $field.'=:'.$field.', '; } // //去掉末尾逗号,并添加符号结束 $sql = rtrim(trim($sql),',').';'; //创建PDO预处理对象 $stmt = $pdo->prepare($sql); //$stmt = $pdo->prepare($sql); //绑定参数到预处理对象 foreach ($data as $field => $value) { $stmt->bindValue(":{$field}",$value); } //执行新增操作 if($stmt->execute()){ if($stmt->rowCount()>0){ return true; }else { return false; } } } } //更新数据 if(!function_exists('update')){ function update($pdo,$table,$data=[],$where=''){ //创建SQL语句 $sql="UPDATE {$table} SET "; foreach(array_keys($data) as $field){ $sql .= $field.'=:'.$field.', '; } $sql = rtrim(trim($sql),','); //添加更新条件 if(!empty($where)){ $sql .=' WHERE '.$where; }else{ die('更新条件不能为空'); } //创建PDO预处理对象 $stmt = $pdo->prepare($sql); //绑定参数 foreach($data as $field => $value){ $stmt->bindValue(":{$field}",$value); } //执行更新操作 if($stmt->execute()){ if($stmt->rowCount()>0){ return true; }else{ return false; } } } } if(!function_exists('find')){ /** * 单条记录查询 * @param $pdo * @return bool */ function find($pdo,$table,$fields,$where){ //创建SQL语句 $sql='SELECT '; if(is_array($fields)){ foreach($fields as $field){ $sql .=$field.', '; } }else{ $sql .=$fields; } $sql=rtrim(trim($sql),','); $sql .=' FROM '.$table; //添加查询语句 if(!empty($where)){ $sql .=' WHERE '.$where; } $sql .=' LIMIT 1'.';'; $stmt =$pdo->prepare($sql); if($stmt->execute()){ if($stmt->rowCount()>0){ $stmt->setFetchMode(PDO::FETCH_ASSOC); return $stmt->fetch(); } }else{ return false; } } } if(!function_exists('select')){ function select($pdo,$table,$fields,$where='',$order=''){ //创建SQL语句 $sql='SELECT '; if(is_array($fields)){ foreach($fields as $field){ $sql .=$field.', '; } }else{ $sql .=$fields; } $sql=rtrim(trim($sql),','); $sql .=' FROM '.$table; //添加查询语句 if(!empty($where)){ $sql .=' WHERE '.$where; } //添加排序条件 if(!empty($order)){ $sql .= ' ORDER BY '.$order .';'; } $stmt = $pdo->prepare($sql); if($stmt->execute()){ if($stmt->rowCount()>0){ $stmt->setFetchMode(PDO::FETCH_ASSOC); //返回一个二维数组 return $stmt->fetchAll(); } }else{ return false; } } } if(!function_exists('delete')){ function delete($pdo,$table,$where){ $sql="DELETE FROM {$table} "; //添加查询语句 if(!empty($where)){ $sql .=' WHERE '.$where.';'; } $stmt=$pdo->prepare($sql); if($stmt->execute()){ if($stmt->rowCount()>0){ return true; } }else{ return false; } } }