框架里自己类

来源:互联网 发布:单片机控制交流电机 编辑:程序博客网 时间:2024/05/18 20:05
在框架的最外层创建一个名为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]);
    }


0 0
原创粉丝点击