abstract://mysqli连接 function connMysqli(){ //连接数据库 $db = @mysqli_connect('127.0.0.1','root','123456','test','3
//mysqli连接 function connMysqli(){ //连接数据库 $db = @mysqli_connect('127.0.0.1','root','123456','test','3306'); if(!$db){ //连接出错,抛出错误 exit('数据库出错:'.mysqli_connect_error()); } //插入数据 $time = time(); $sql = "insert into `user`(`name`,`sex`,`age`,`email`,`password`,`status`,`create_time`) values('包惜弱',1,18,'hzh@php.com',sha1(123456),1,$time);"; $res = $this->insert_func($db,$sql); //修改数据 $sql = "update `user` set `age` = 46,`status` = 0 where id = 10;"; $res = $this->save_func($db,$sql); //删除数据 $sql = "delete from `user` where `id` = 5;"; $res = $this->save_func($db,$sql); //查询 $sql = "select * from `user`"; $sql = "select * from `user` limit 0,5";//分页 $sql = "select * from `user` order by `create_time` desc";//排序 $sql = "select count(*) from `user`";//聚合函数:统计 $res = mysqli_query($db,$sql); $list = $this->select_func($db,$sql); echo '<pre>';print_r($list); mysqli_close($db);//关闭数据库连接 } //查询方法 function select_func($db,$sql){ $res = mysqli_query($db,$sql); if($res){ while ($item = mysqli_fetch_assoc($res)){ $list[] = $item; } mysqli_free_result($res); } return $list; } //删除、修改方法 function save_func($db,$sql){ $res = mysqli_query($db,$sql); return $res; } //插入方法 function insert_func($db,$sql){ $res = mysqli_query($db,$sql); if($res){ $res = mysqli_insert_id($db); } return $res; } 查询的操作比修改和删除的都复杂,在实际应用中用到的更多的是查询操作。
Correcting teacher:韦小宝Correction time:2018-12-14 16:02:43
Teacher's summary:写的很不错!mysqli连接数据库也是非常常用的方法之一!