<?php /** * Created by PhpStorm. * User: Jason * Date: 2019/4/8 * Time: 21:58 */ # mysqli 方法库 # 连接数据库 /*$conn = @mysqli_connect('127.0.0.1','root','root','php_edu','3306'); if(!$conn) { # 连接错误,抛出异常 exit('数据库报错:'.mysqli_connect_errnr()); }*/ # 组装插入数据 /*$add_time = time(); $sql = "INSERT INTO `director` (name,phone,country,add_time) VALUES ('一本道','18899876578','***','{$add_time}')"; $rs = insert($conn,$sql); var_dump($rs);*/ /*$add_time = time(); $sql = "INSERT INTO `users` (name,phone,country,birthday,weight,height,add_time) VALUES ('逆风局','15129216568','***','1989-09-19',100,165,'{$add_time}')"; $rs = insert($conn,$sql); var_dump($rs);*/ # 修改数据 #$sql = "UPDATE `director` SET name='金山毒' WHERE tid=3;"; # 删除操作 #$sql = "DELETE FROM `director` WHERE tid = 3;"; # 查询数据 //$sql = "SELECT * FROM `users` LIMIT 0,2"; //$sql = "SELECT * FROM `users` ORDER BY uid DESC LIMIT 0,3"; /*$res = select($conn,'users','country="***"','uid asc','0,3'); echo '<pre>'; print_r($res);*/ #查询一条数据 /*$res = find($conn,'users','country="***"','uid DESC','name'); print_r($res);*/ # 查询统计 /*$res = count_number($conn,'users','country="***"'); print_r($res);*/ # 关闭数据库 //mysqli_close($conn); # 连接方法 function connect($db) { $conn = @mysqli_connect($db['host'],$db['user'],$db['pwd'],$db['dbname'],'3306'); if(!$conn) { # 连接错误,抛出异常 exit('数据库报错:'.mysqli_connect_errnr()); } return $conn; } # 统计数量 function count_number($conn,$table,$where) { $sql = "SELECT count(*) AS counts FROM `{$table}` ". ' WHERE '.$where; $res = mysqli_query($conn,$sql); $ret = mysqli_fetch_assoc($res); # 关闭数据库 mysqli_close($conn); return $ret['counts']; } #查询和一条数据 function find($conn,$table,$where,$order='uid asc',$field='*') { $sql = "SELECT {$field} FROM ".$table.' WHERE '.$where.' ORDER BY '. $order .' LIMIT 1'; $res = mysqli_query($conn,$sql); $ret = mysqli_fetch_assoc($res); mysqli_free_result($res); # 关闭数据库 mysqli_close($conn); return $ret; } # 查询数据 function select($conn,$table,$where,$order,$limit=0,$field='*') { $sql = "SELECT {$field} FROM ".$table.' WHERE '.$where.' ORDER BY '.$order; if($limit) { $sql .= " LIMIT ".$limit; } $res = mysqli_query($conn,$sql); $ret = null; if($res){ //$ret = mysqli_fetch_all($res); $ret = mysqli_fetch_all($res,MYSQLI_ASSOC); } // 释放内存 mysqli_free_result($res); # 关闭数据库 mysqli_close($conn); return $ret; } # 插入数据 function insert($conn,$sql) { # 执行插入 $insert = mysqli_query($conn,$sql); if($insert) { // 返回插入的自增ID $insert = mysqli_insert_id($conn); } # 关闭数据库 mysqli_close($conn); return $insert; } # 修改方法 function save($conn,$sql) { $insert = mysqli_query($conn,$sql); # 关闭数据库 mysqli_close($conn); return $insert; } # 删除数据 function delete($conn,$sql) { $insert = mysqli_query($conn,$sql); # 关闭数据库 mysqli_close($conn); return $insert; }