Hi I'm creating a multiple search form where in it could detect if the field doesnt have any values and would still search if 1 or more fields has input. But i can't seem to generate the correct sql statement for this.
<form method="post" action="#" id="searchform">
First Name:<br>
<input type="text" name="fname">
<br>Last Name:<br>
<input type="text" name="lname">
<br>Email: <br>
<input type="text" name="email">
<br>
<input type="submit" name="submit" value="Search">
</form>
if(!empty($sfname) || !empty($slname) || !empty($semail)){
$emailQueryPart = !empty($semail) ? "Email LIKE '%$semail%'" : "";
$lastnameQueryPart = !empty($slname) ? "LastName LIKE '%$slname%'" : "";
$firstnameQueryPart = !empty($sfname) ? "FirstName LIKE '%$sfname%'" : "";
$arr = array($emailQueryPart, $lastnameQueryPart,$firstnameQueryPart);
$sql = "select * from Userlist where";
for($i = 0; $i <= count($arr); $i++)
{
if(!empty($arr[$i]))
{
if($i >= 2)
{
$sql.=" AND ";
}
if($i > 0)
{
$sql.= " " .$arr[$i];
}
}
}
}else{
echo "You must enter at least one value";
}
echo $sql;
Known Problems. 1. "Email" value doesnt show up even if i input a value, it only shows "select * from Userlist where " 2. If i only input in the firstname AND shows early, im probably wrong on how i placed my if statement for adding the "AND" sample result is "select * from Userlist where AND FirstName LIKE '%test%' "
Aucun commentaire:
Enregistrer un commentaire