您的位置:首页 > 数据库

2016/3/27 ①连接数据库方法的封装 ②连接数据库 制表 网页查询 奥迪

2016-03-27 12:35 549 查看
①连接数据库方法的封装

<?php
class DBDA
{
public $host="localhost";//服务器地址
public $uid="root";//数据库的用户名
public $pwd="123";// 数据库的密码
//public $dbname="test2";
//默认要操作的数据库
//函数 1 代表查询
//执行sql语句,返回相应结果的函数
//$sql是要执行的SQL语句
//$type是SQL语句的类型,0代表增删改,1代表查询
//$db代表要操作的数据库
public function Query($sql,$type=1,$db="test2")
{
//造连接对象
$conn=new mysqli($this->host,$this->uid,$this->pwd,$db);

//判断连接是否成功
!mysqli_connect_error()or die("连接失败!");
//执行SQL语句
$result=$conn->query($sql);

//判断SQL语句类型
if ($type=1)
{    //如果是查询语句返回结果集
return $result->fetch_all();
}
else
{    //如果是其他语句,返回true或false
return $result;
}
}

}
?>


②连接数据库后的查询

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
<form action="testchaxun.php" method="post">
<div>
<input type="text" name="name"/>
<input type="text" name="price"/>
<input type="submit" value="查询"/>
</div>
</form>
</div>
<table width="100%" cellspacing="0" cellpadding="0" border="1">
<tr>

<td>代号</td>
<td>名称</td>
<td>价格</td>
</tr>
<?php
//include 类出现错误 下面代码继续执行
//require 出现错误 下面代码不继续执行
include("DBDA.php");
$db=new DBDA();

@$name=$_POST["name"];
@$price=$_POST["price"];

$st1="";
$st2="";
if ($name !="") {
$st1=" Name like '%{$name}%'";
}
else{
$st1=" 1=1";
}
if ($price !="") {
$st2=" Price = {$price}";
}
else{
$st2=" 1=1";
}
$str=" where".$st1." and ".$st2;

//这个方法不好实现
// if ($name=="" && $price=="")
//  {

// }
// else{
//     if ($name!="") {
//         $str=$str." where Name like '%{$name}%'";
//     }
//     if ($Price!="") {

//     }
// }
// if ($name!="") {
//     $str=$str." where Name like '%{$name}%'";
// }

//写SQL语句
$sql="select Code,Name,Price from Car".$str;
echo $sql;
//调用类里面的query方法执行sql语句
$attr=$db->query($sql);

for ($i=0; $i < count($attr); $i++)
{    //关键字变色处理
$mc=str_replace($name, "<mark><span style='color:red'>{$name}</span></mark>", $attr[$i][1]);

//str_replace(search, replace, subject)

echo "<tr><td>{$attr[$i][0]}</td><td>{$mc}</td><td>{$attr[$i][2]}</td></tr>";
}

?>
</table>
</body>
</html>


显示效果:







内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: