zoukankan      html  css  js  c++  java
  • 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="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>
  • 相关阅读:
    vue3 祖孙传递数据
    vue 导航栏不能收缩的问题
    vue 项目中的问题
    Python第一周Round1记录
    [转]80端口被系统占用pid=4: NT kernel & System
    表<表名称> 中的列与现有的主键或UNIQUE约束不匹配
    一些算法(2)
    卸载不了java(tm)se development kit 7 update 3
    如何解决 Eclipse中出现访问限制由于对必需的库XX具有一定限制,因此无法访问类型
    [COPY]Eclipse无法导入项目
  • 原文地址:https://www.cnblogs.com/yshyee/p/3394848.html
Copyright © 2011-2022 走看看