条件查询php

时间:2021-04-12 17:50:06

页面1.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> <h1>信息</h1>
<form action="1.php" method="post">
<div>
请输入姓名:<input type="text" name="name" />
  电话:<input type="text" name="tel" />
<input type="submit" value="查询" />
</div>
</form>
<br />
<table width="100%" border="1" cellpadding="0" cellspacing="0"> <tr>
<td>代号</td>
<td>姓名</td>
<td>电话</td>
<td>分组</td>
</tr> <?php //实现两个逻辑
//1.如果没有POST数据,查所有
//2.如果有POST数据,根据条件查 $db = new MySQLi("localhost","root","root","dbname"); /*if(POST传值)
{
SQL语句1
}
else
{
SQL语句2
}
*/ $tj = " 1=1 "; //默认条件,前后最好带有空格
$tj2 =" 1=1 ";
$name = "";//外面要写一个默认值,若不写,当不走if时会没有值
$tel = "";
if(!empty($_POST["name"]))
{
$name = $_POST["name"];
$tj = " Name like '%{$name}%' ";
}
if(!empty($_POST["tel"]))
{
$tel = $_POST["tel"];
$tj = " Tel = '{$tel}' ";
}
//将条件拼接到SQL语句
$sql = "select * from contacts where {$tj} and {$tj2}";
//echo $sql; 
$result = $db->query($sql);
while($arr = $result->fetch_row()) {
//关键字的特殊显示
$str = str_replace($name,"<mark>{$name}</mark>",$arr[1]);
//查找替换
//substr_replace(); //指定位置替换
echo "<tr> <td>{$arr[0]}</td>
<td>{$str}</td>
<td>{$arr[2]}</td>
<td>{$arr[3]}</td>
</tr>"; }
?>
</table>
</body>
</html>