您的位置 >>> 星想互联 >>> 编程技术 >>> PHP基础
学习笔记:MySqli封装的数据库操作类
点击数:2401  发布时间2017-09-19 16:41:35

<?php
 header("Content-type: text/html; charset=gb2312"); 

class mydb{
 public $dbinfo =array(
  "host"=>"localhost",
  "user"=>"root",
  "pwd"=>"",
  "dbname"=>"news",
  "ci"=>"set names gb2312"
 );

 public $link;

 public function connect(){
        $host=$this->dbinfo['host'];
        $user=$this->dbinfo['user'];
        $pwd =$this->dbinfo['pwd'];
        $dbname=$this->dbinfo['dbname'];
        $ci=$this->dbinfo['ci'];
        $conn= new mysqli($host,$user,$pwd,$dbname);
        $this->link=$conn;
        $this->link->query($ci);
     }
   
    public function query($sql){
         $stmt=$this->link->query($sql);
         if(!$stmt){
    echo "操作成功";
         }else{
          echo "操作失败";
         }
    }

    public function getRow($sql){
         $stmt=$this->link->query($sql);
         $row=$stmt->fetch_array(MYSQLI_ASSOC);
         return $row;
    }

    public function getAll($sql){
         $stmt=$this->link->query($sql);
         $rows=$stmt->fetch_all(MYSQLI_ASSOC);
         return $rows;
    }

}

//数据操作
$mydata=new mydb();
$mydata->connect();
$rs=$mydata->getRow("selects id,title from news limit 0,5");
echo $rs['title'];
echo "<hr>";

$rs=$mydata->getAll("selects id,title from news limit 0,5");
var_dump($rs);
?>

来源:咸宁网站建设