Reputation: 3
i'm trying with search box in php my html form have three options like below
i want if user select purpose data filter by purpose, if type then filter by type and if location then filter by location and if he select all categories then it filter like purpose in type in location and if not match display (Result not found!)
i used these php queries but fail to get
$res="SELECT * FROM test WHERE purpose like %$_Post['purpose']% AND type like %$_Post['type']% AND location like %$_Post['location']%";
while ($row = mysql_fetch_array($res))
{
echo $row['purpose']."</br>";
echo $row['type']."<br>";
echo $row['location'];
}
but this query not filter one by one it show if all selected if i use OR instead of AND then mix result found but i want Purpose in type in location
and if not found show Result not found
please write complete query
thanks
Upvotes: 0
Views: 327
Reputation: 1253
$dbc = mysqli_connect('host', 'user', 'password', 'database') or die('Error connecting to MySQL server');
if (isset($_POST['purpose'])) $where.= " AND purpose LIKE %". mysqli_real_escape_string($dbc, $_POST['purpose'])."%";
if (isset($_POST['type'])) $where.= " AND type LIKE %". mysqli_real_escape_string($dbc, $_POST['type'])."%";
if (isset($_POST['location'])) $where.= " AND location LIKE %". mysqli_real_escape_string($dbc, $_POST['location'])."%";
$res="SELECT * FROM test
WHERE 1=1
". ($where? $where: "");
while ($row = mysql_fetch_array($res)) {
echo $row['purpose']."</br>";
echo $row['type']."<br>";
echo $row['location'];
}
Upvotes: 0
Reputation: 11374
$_POST
not $_Post
, case matters.You need to be sure your code is safe, do not ever use values without escaping them.
$purpose = mysqli_real_escape_string($dbc, $_POST['purpose' ]);
$type = mysqli_real_escape_string($dbc, $_POST['type' ]);
$location = mysqli_real_escape_string($dbc, $_POST['location']);
Edit: Removed my query as @Martin's is correct, this one wasn't.
Upvotes: 1