Reputation: 59
I have a search form which has four filter textboxes. What I want to do is whenever the user submits the form, only those textboxes that has values will be submitted and searched for. I know how to do it in if else statement, but it's too long to write it in code. Is there any other shorter methods?
Upvotes: 0
Views: 74
Reputation: 286
Process.php
<?php
if (($_POST['First'])== TRUE);
$Fv = $_POST['First'];
if(($_POST['Second'])== TRUE);
$Sv = $_POST['Second'];
if(($_POST['Third'])!= TRUE);
$Tv = $_POST['Third'];
if(($_POST['Fourth'])!= TRUE);
$Fov = $_POST['Fourth'];
echo $Fv;
echo"</br>";
echo $Sv;
echo"</br>";
echo $Tv;
echo"</br>";
echo $Fov;
?>
search.php
<?php
echo '<html>
<body>
<form action="process.php" method="post">
First: <input type="text" name="First"><br>
Second: <input type="text" name="Second"><br>
Third: <input type="text" name="Third"><br>
Fourth: <input type="text" name="Fourth"><br>
<input type="submit">
</form>
</body>
</html> ';
?>
Only the values entered with be echoed.
Upvotes: 1
Reputation: 543
Try this one search.php
$sql = " select * from table name where 1=1 "
if (($_POST['First'])!='');
$sql .= ' AND first = "'.$_POST['First'].'"';
if(($_POST['Second'])!='');
$sql .= ' AND Second = "'.$_POST['Second'].'"';
if(($_POST['Third'])!='');
$sql .= ' AND Third = "'.$_POST['Third'].'"';
if(($_POST['Fourth'])!='');
$sql .= ' AND Fourth = "'.$_POST['Fourth'].'"';
Or try this
$arr = $_POST;
$sql = " select * from table name where 1=1 "
foreach($arr as $key =>$ar){
if($ar!='') $sql .= ' AND '.$key.' = "'.$ar.'"';
}
The input name and db field name must be same...
Upvotes: 1
Reputation: 2088
Try to use this code. You can implement search condition in the foreach loop.
// HTML field names
$fields = array_flip(array("search1", "search2", "search3", "search4"));
$data = array_filter(array_intersect_key($_POST, $fields));
foreach ($data as $key => $val) {
// Here you can implement the sql search condtion
echo "$key => $val" . PHP_EOL;
}
Upvotes: 0