php的数据访问和封装运用

php数据访问:

<!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

//建一个连接,造一个连接对象
$db = new MySQLi("localhost","root","123","mydb");

//判断是否出错
/*if(mysqli_connect_error())
{
echo "连接失败!";
exit;
}*/

mysqli_connect_error()?die("连接失败"):"";

//写SQL语句
$sql = "select * from Info";

//执行SQL语句,返回结果集对象
$reslut = $db->query($sql);

//从结果集中读取数据,返回数组
//$attr = $reslut->fetch_all(); //读取所有数据,返回索引二维数组

//$attr = $reslut->fetch_array(); //读取当前指针指向的数据,返回索引关联都存在的数组

//$attr = $reslut->fetch_assoc(); //返回关联数组

//$attr = $reslut->fetch_row(); //返回索引数组

//$attr = $reslut->fetch_object(); //返回对象
/*$arr = array();
while($attr = $reslut->fetch_row())
{
array_push($arr,$attr);
}

var_dump($arr);*/

?>

</body>
</html>

  封装:

<?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
}
}
}
?>

   引用到界面:

<!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>

原文地址:https://www.cnblogs.com/chenshanhe/p/6839379.html