您的位置:首页 > 编程语言 > PHP开发

PHP语言 -- 封装连接数据库类

2016-04-17 11:05 337 查看
<?php

class DBDA
{
public $host = "localhost"; //服务器地址
public $uid = "root";//数据库用户名
public $pwd = "123";//数据库密码

//执行SQL语句,返回相应结果的函数
//$sql 是要执行的SQL语句
//$type 是SQL语句的类型,0代表增删改  1代表查询
//$db  代表要操作的数据库

pulic function Query($sql,$type=1,$db = "mydb")
{
//造连接对象
$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;
}

}

}


单条件查询

<body>
<div>
<form action="当前页面" method="post"> //造查询框和按钮

<div>
名称:
<input type="text" name="name"/>

<input type="submit" value="查询"/>
</div>

</form>
</div>
<br/>

<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>//表头
<td>代号</td>
<td>名称</td>
<td>价格</td>
</tr>
<?php
include("DBDA.php");

$db = new DBDA();

$str="";
if(!empty($_POST["name"]))
{
$name = $_POST["name"];

if($name!="")  //空字符串也不是空的 需要判断
{
$str= $str." where Name like '%{$name}%'"
}
}

//写SQL语句
$sql="select Code,Name,Price from Car".$str;

//调用类里面的query方法执行SQL语句
$attr = $db->Query($sql);

for($i =0;$i<count($attr);$i++)
{
$attr[$i]
echo "<tr><td>{$attr[$i][0]}</td><td>{$attr[$i][1]}</td><td>{$attr[$i][2]}</td></tr>";
}
?>
</table>
</body>


多条件查询 并且关键字高亮显示

<body>
<div>
<form action="当前页面" method="post"> //造查询框和按钮

<div>
名称:
<input type="text" name="name"/>
价格:
<input type = "text" name="price"/>
<input type="submit" value="查询"/>
</div>

</form>
</div>
<br/>

<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>//表头
<td>代号</td>
<td>名称</td>
<td>价格</td>
</tr>
<?php
include("DBDA.php");

$db = new DBDA();

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

$tj1 = " 1=1";
$tj2 = " 1=1";
if($name!="")
{
$th1= " Name like '%{$name}%'";
}

if($price!="")
{
$tj2=" Price ={$price}";
}

$str= " where".$tj1." and".$tj2;

//写SQL语句
$sql="select Code,Name,Price from Car".$str;

//调用类里面的query方法执行SQL语句
$attr = $db->Query($sql);

for($i =0;$i<count($attr);$i++)
{
//关键字变色处理
$mc = str_replace($name,"<span style="color:red">{$name}</span>",$attr[$i][1]);
echo "<tr><td>{$attr[$i][0]}</td><td>{$mc}</td><td>{$attr[$i][2]}</td></tr>";
}
?>
</table>
</body>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: