php 之mysqli简单封装

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> &nbsp;|&nbsp;
        <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>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值