框架里自己类

    xiaoxiao2021-03-26  25

    在框架的最外层创建一个名为mydb.php的文件

    <?php

    namespace app; class mydb {     public $host="127.0.0.1";     public $name="root";     public $dbname='taobao';     public $table='myuser';     public $link;     public function __construct()     {         // 连接数据库         $this->link=mysqli_connect('127.0.0.1','root','root',"taobao");        $sql="set names utf8";;        mysqli_query($this->link,$sql);     }     // /  执行  sql查询 语句     public function query($sql)     {       return mysqli_query($this->link,$sql);     }     //  返回一行数据查询的结果      public function getOne($field="*",$where="")      {         $sql="select ".$field." from ".$this->table." ".$where;          $res=mysqli_query($this->link,$sql);         $row=mysqli_fetch_assoc($res);         return $row;      }     // 执行一条sql     public function getRow($sql)     {         $sql='select * from '.$this->table;         return mysql_fetch_assoc($this->query($sql));     }     // 返回数据库查询结果     public function getAll($where="")     {          $sql="select * from myuser"." ".$where;           // return  $sql;            $res=mysqli_query($this->link,$sql);          while($row=mysqli_fetch_assoc($res)){             $data[]=$row;          }                    return $data;     }

    }

    第二部,如果用框架里引入类这样写

    public function actionIndex()     {          $db=new mydb();        $request=Yii::$app->request;         $page=$request->get('page');          // 煤业条数           $per_page=4;           // 总条数         $num=$db->getOne('count(id) as num');          //便宜量         // 总页码          $num=$num['num'];         // var_dump($num);die;          $last_page=ceil($num/$per_page);          // var_dump($last_page);die;         $offset=empty($page)?0:($page-1)*$per_page;        //  查询数据         // var_dump($num);die;         $where=' limit '.$offset.','.$per_page;         $data=$db->getAll($where);         // var_dump($data);die;       return  $this->render('show',['data'=>$data,'page'=>$page,'last_page'=>$last_page]);     }

    转载请注明原文地址: https://ju.6miu.com/read-660172.html

    最新回复(0)