SoFunction
Updated on 2025-04-13

PHP combination query multi-condition query instance code


<?php
$link = mysql_connect("localhost","root","administrator password");
mysql_select_db("infosystem", $link);
?> 

<?php

//Note 1-------------------------------------------------------------------------------------------------------------------------
$depart=$_POST["depart"];
$ename=$_POST["ename"];

//Note 2-------------------------------------------------------------------------------------------------------------------------
if($depart != null){
$a = " and depart like '%$depart%'";}

if($ename != null){
$b = " and ename like '%$ename%'";}

//Note 3-------------------------------------------------------------------------------------------------------------------------
$q = "SELECT * FROM info where (1=1)";
$q .=$a;
$q .=$b;


//Note 4-------------------------------------------------------------------------------------------------------------------------
mysql_query("SET NAMES GB2312");
$rs = mysql_query($q, $link);
echo "<table>";
echo "<tr><td>Department</td><td>Employee Name</td></tr>";
while($row = mysql_fetch_object($rs)) echo "<tr><td>$row->depart</td><td>$row->ename</td></tr>";
echo "</table>";

mysql_close($link);

?>
Note 1: Receive the parameters passed through post and store the two parameters into variables: depart and name.

Comment 2: Determine whether the parameter is empty. If it is empty, no operation will be performed. If any parameters are passed out, the corresponding SQL statement is generated.

Comment 3: Use append method to generate SQL statements.

Comment 4: Generate the data set, display the data, and finally close the database connection.

How about it, is the function of combining query implemented? If you have the chance, I will introduce it in more detail.

This article is reproduced from