php数据访问(查询)

时间:2022-09-08 06:33:58

查询:常用关键字查询 和 准确查询

单条件查询

创建添加查询元素

<br />
<form action="main.php" method="post">
<div>姓名:
  <input type="text" name="xm" />
  <input type="submit" value="查询" />
</div>
</form>
<br />

先判断有没有提交值

$xm="";                         //定义一个空字符串xm
if(!empty($_POST["xm"])) //判断是否有传的值
{
$xm = $_POST["xm"]; //如果不为空,把值取出存到$xm中。 这里直接取值会报错,所以要加if判断,如果不报错是完全可以的
} $tj = ""; //定义一个空字符串tj
if($xm == "") //判断$xm是否为空
{
$tj = " 1=1 "; //如果为空,查所有
}
else
{
$tj = " name='{$xm}' "; //如果不为空,就根据name的$xm值来进行查询
}

SQL语句满足查询条件

$sql = "select * from info where ".$tj;

给关键字特殊显示

给关键字特殊显示
$xxm =""; //空字符串$xxm
if(!empty($_POST["xm"])) //不能直接取值还是要用if判断
{
$xxm = $_POST["xm"];
}

根据关键字从字符串里边替换

$newname = str_replace($xxm,"<mark>{$xxm}</mark>",$v[1]);    //三个元素分别为  关键字、要替换的东西、要替换的字符串

多条件查询

    $xxm = "";
$tj = " 1=1 ";
$tj2 = " 1=1 ";
if(!empty($_POST["xm"]) && $_POST["xm"]!="") //条件1
{
$xxm = $_POST["xm"];
$tj = " name like '%{$xxm}%' ";
} if(!empty($_POST["mz"]) && $_POST["mz"]!="") //条件2
{
$mz = $_POST["mz"];
$tj2 = " nation='{$mz}' ";
} //连接对象
$db = new MySQLi("localhost","root","123","mydb"); //SQL语句
$sql = "select * from info where ".$tj." and ".$tj2; //满足两个条件 echo $sql;