在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1:DBHelper.class.php <?php class DBHelper{ private $mysqli; private static $host='127.0.0.1'; private static $user='root'; private static $pwd='mysql'; private static $dbname='test'; //通过构造方法进行初始化操作 public function __construct(){ $this->mysqli=new mysqli(self::$host,self::$user,self::$pwd,self::$dbname) or die('数据库链接出错:'.$this->mysqli->connect_error); //设置数据库编码为utf8 $this->mysqli->query('set names utf8'); } //执行查询语句 public function execute_dml($sql){ $arr=array(); $result=$this->mysqli->query($sql) or die($this->mysqli->error); if($result){ while($row=$result->fetch_assoc()){ //将查询结果封装到一个数组中,返回给方法调用处 $arr[]=$row; } //释放查询结果资源 $result->free(); } return $arr; } //执行增加、删除、更新语句 public function execute_dql($sql){ $result=$this->mysqli->query($sql) or die($this->mysqli->error); if(!$result){ return 0;//表示操作失败 }else{ if($this->mysqli->affected_rows>0){ return 1;//操作成功 }else{ return 2;//没有受影响的行 } } } } ?> 2:使用案例index.php <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <?php require_once('DBHelper.class.php'); $dbhelper=new DBHelper(); $sql='select id,name,age from user'; $users=$dbhelper->execute_dml($sql); if(!empty($users)){ ?> <table style="width:80%;"> <tr> <th>ID</th> <th>Name</th> <th>Age</th> <th>操作</th> </tr> <?php foreach($users as $user){ ?> <tr align='center'> <td><?php echo $user['id'];?></td> <td><?php echo $user['name'];?></td> <td><?php echo $user['age'];?></td> <td> <a href="delete.php?id=<?php echo $user['id'];?>">Delete</a> | <a href="show.php?id=<?php echo $user['id'];?>">Show</a> </td> </tr> <?php }?> </table> <?php }else{ echo '<h1>No result!</h1>'; } ?> <hr/> <a href="add.php" style="font-size:24px;font-weight:bold;">Add a new user</a> </body> </html>
|
2022-08-17
2022-11-06
2022-08-18
2022-08-15
2022-08-16
请发表评论