TypechoJoeTheme

轩宇网

PHP数据访问之封装类

一、封装类的目的:

封装类是为了更方便在多个地方使用数据库,避免复杂的代码。

二、封装类:

由于调用数据库要用到四个参数:地址,用户名,密码,数据库名称,所以封装类就包括了以上四个对象。代码如下:

DB.class.php

<?php
class DB
{
    public $host="localhost";
    public $uid="root";
    public $pwd="123";
    public $dbname="text_0306";

//执行sql语句,返回相应结果
//sql要执行的sql语句
//$type代表sql语句的类型,0代表增删改,1代表查询
function query($sql,$type=1)
{
    $db=new MySQLi($this->host,$this->uid,$this->pwd,$this->dbname);
    $result=$db->query($sql);
    if($type)
    {
        //如果是查询,返回数组
        return $result->fetch_all();    
    }
    else
    {
        //如果是增删改,返回true或false
        return $result;    
        }
    }
}
?>

三、封装类的调用:

<?php
$id=$_GET["id"];//提取数据
require "DB.class.php";//调用封装类
$db=new DB;//造对象
$sql="select*from news where id='{$id}'";
$result=$db->query(($sql));
$arr=$result->fetch_row();
?>
赞(0)