第1步:建一个封装类的文件DBDA.class.php
<?php
//建一个封装类的文件DBDA.class.php
class DBDA//定义一个类,类名为DBDA
{
public $host="localhost";//4个比较常用的参数:服务器地址
public $uid="root";//用户名
public $pdw="666";//密码
public $dbname="toupiao";//数据库名称
//封装方法
//1.返回二维数组的方法
/**
*给一个sql语句,返回执行的结果
*@param string $sql 用户指定的sql语句
*@param int $sql用户给的语句类型,0代表增删改,1代表查询。一般查询使用的比较多,让$type的默认值为1.如果是增删改再改$type的值。
*@return array 返回查询的结果,如果是查询,返回二维数组。如果是增删改,返回$result。
*/
function Query($sql,$type=1)
{
//造连接对象
$db = new MySQLi("$this->host","$this->uid","$this->pdw","$this->dbname");
//执行sql语句
$result = $db->query("$sql");
//从结果集对象里取数据。查询单独做一个方法,其它做另一个方法。
if($type==1)//如果是查询
{
return $result->fetch_all();//返回查询的二维数组
}
else//如果是增删改
{
return $result;//返回$result
}
}
}
第2步:将封装的类引用到页面中
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body>
<?php
include("DBDA.class.php");//将封装的类引入此页面
$db = new DBDA();//新建一个对象
$sql = "select * from info";
var_dump($db->Query($sql));//第2个参数不写的话就是查询,因为默认值是1.
?>
</body> </html>
