代码如下
<?php /** * 操作函数库 */ if (!function_exists('connect')){ // 数据库连接 function connect($dbname,$type='mysql',$host='127.0.0.1', $charset='utf8',$user='root',$password='root'){ $dsn = "{$type}:host={$host}; dbname={$dbname}; charset={$charset}"; $userName = 'root'; $password = 'root'; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_NATURAL, PDO::ATTR_EMULATE_PREPARES => true,]; try { $pdo = new PDO($dsn, $userName, $password, $options); }catch (PDOException $e) { die('Connect ERROR!:'.$e->getMessage()); } return $pdo; } } //新增数据 if (!function_exists('insert')){ function insert($pdo, $table, $data=[]) { $sql = "INSERT IGNORE {$table} SET "; foreach (array_keys($data) as $field) { $sql .= $field . '=:' . $field . ', '; } $sql = rtrim(trim($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 = "UPDATE {$table} SET "; foreach (array_keys($data) as $field) { $sql .= $field.'=:'.$field.', '; } $sql = rtrim(trim($sql),','); if(!empty($where)) { $sql .= ' WHERE '. $where; }else{ exit('不能为空'); } $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('select')) { function select($pdo,$table,$fields, $where='', $order='') { $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; } $sql = rtrim(trim($sql),',').';'; $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; }else{ exit('条件不能为空'); } $sql = rtrim(trim($sql),',').';'; $stmt = $pdo->prepare($sql); if($stmt->execute()){ if($stmt->rowCount()>0){ return true; } } else { return false; } } }
手写如下