封装类方式访问数据库

封装类页面(Dbda.class.php)

<?php
//封装类的方式访问数据库,更易于维护,只修改类的相关内容即可
header("content-type:text/html;charset=utf-8");
class DBDA
{    
    public $host="localhost";
    public $uid="root";
    public $pwd="123";
    public $dbconnect;    //成员变量可以是连接对象
    
    //操作数据库的方法 
    function query($sql,$type=1,$dbname="info")//$type=1代表查询,其他为增删改,$dbname数据库名称
    {    
        //造连接对象
        $this->dbconnect=new MySQLi($this->host,$this->uid,$this->pwd,$dbname);//没有$daconnect无法实现这一步
        //判断连接是否成功
        if(!mysqli_connect_error())
        {
            $result=$this->dbconnect->query($sql);
            if($type==1)
            {
                //查询语句,返回二维数组
                return $result->fetch_all();
                
            }
            else
            {    //增删改语句返回true 或 false
                return $result;
            }
        }
        else
        {
            echo "连接失败";
        }
    }
    
}

操作页面:

<table width="100%" border="1" cellpadding="0" cellspacing="0">
<?php
include "Dbda.class.php";
$if=new DBDA();
$sql="select * from nation";
$attr=$if->query($sql);
foreach($attr as $v)
{
    echo "<tr>
    <td>{$v[0]}</td>
    <td>{$v[1]}</td>
    </tr>";
}

$i=new Dbda();
$sql="insert into family (ids) values('')";
$q=$i->query($sql,0);
var_dump($q);
echo $i->dbconnect->insert_id;//获取到上一条添加数据的主键值
$sql="delete from family where ids not in(1,2,3,4,5,6,7,8,9,10)";
$i->query($sql,0);
?>
</table>
原文地址:https://www.cnblogs.com/jinshui/p/5590801.html