PHP advanced search with Multiple OPTION - php

I am building a search field with php where users can search for Doctors information with multiple search options.
As shown in the picture a user can search by: DR.NAME, SPECIALTY, DIVISION, LOCATION. The DR.NAME should match any keyword and the form doesn't require any fields to be filled out.
This is my current code which isn't working.
doctorsearch.php
<?php
error_reporting(0);
include 'config.php';
$d_fname = $_POST['d_fname'];
$d_spcl = $_POST['d_spcl'];
$d_division = $_POST['d_division'];
$d_location = $_POST['d_location'];
$qry = "SELECT * FROM doctor_reg WHERE ";
if ($d_fname != '') {
$qry .= "d_fname='".mysql_real_escape_string($d_fname)."' AND ";
}
if ($d_spcl != '') {
$qry .= "d_spcl='".mysql_real_escape_string($d_spcl)."' AND ";
}
if ($d_division != '') {
$qry .= "d_division='".mysql_real_escape_string($d_division)."' AND ";
}
if ($d_location != '') {
$qry .= "d_location='".mysql_real_escape_string($d_location)."' AND ";
}
$result = mysql_query($result);
?>
<?php
echo "<table border='1px solid #CCCCCC;' width='100%'>";
echo "<tr style='color:#FFFFFF;background:#555555;'>";
echo "<th style='padding:3px;'>Name</th>";
while($row = mysql_fetch_array($result)){
echo "<tr class='trbd'>";
echo "<td style='padding:3px;'>".$row['d_fname'].' '.$row['d_lname']."</td>";
?>
<?php
echo "</tr>";
}
echo "</table>";
?>

if you want any keyword not exact match then you shoud use like instead of = operator, so change this
if ($d_fname != '') {
$qry .= "d_fname='".mysql_real_escape_string($d_fname)."' AND ";
}
into this
if ($d_fname != '') {
$qry .= "d_fname LIKE'%".mysql_real_escape_string($d_fname)."%' AND ";
}

You need to add OR instead of AND.
Generally, when users search they search by OR condition.
For example: Doctor Name should be Sharma or location should be east street.
If we search with AND conditions, database will search only records who have the exact combination.
AND returns true if all the conditions are true.
OR returns true if any of conditions is true.
Therefore, OR is correct syntax here.
Corrected code:
$qry = "SELECT * FROM doctor_reg";
$searchArray = array();
if ($d_fname != '') {
$searchArray[] = "d_fname LIKE '%".mysql_real_escape_string($d_fname) . "%'";
}
if ($d_spcl != '') {
$searchArray[] = "d_spcl LIKE '%".mysql_real_escape_string($d_spcl) . "%'";
}
if ($d_division != '') {
$searchArray[] = "d_division LIKE '%".mysql_real_escape_string($d_division) . "%'";
}
if ($d_location != '') {
$searchArray[] = "d_location LIKE '%".mysql_real_escape_string($d_location) . "%'";
}
$qry .= ! empty($searchArray) ? " WHERE " . implode(" OR ", $searchArray) : '';

Related

Filter data from database with multiple user selections

Currently I'm developing a search form so my SQL query needs to change with user input. Please see the below code sample.
$sqlSearch = "SELECT * FROM seafarers WHERE ";
if ($dateS != "") {
$sqlSearch .= "add_date = '" . changeDateSlashToHypen($dateS) . "' and ";
}
if ($cdcS != "") {
$sqlSearch .= "cdc = '" . $cdcS . "' and ";
}
if ($ppS != "") {
$sqlSearch .= "passport LIKE '%$ppS%' and ";
}
if ($surnameS != "") {
$sqlSearch .= "surname LIKE '" . $surnameS . "%' and ";
In order to execute this statement the user must select all the options; the statement will not work if the user selects one or two options.
Don't patch your query together like this. Use Prepared Statements. Example:
SELECT *
FROM seafarers
WHERE (:dt is null or add_date = :dt)
and (:cdc is null or cdc = :cdc)
You have to fill the parameters of the query before execution.
Start out with a placeholder like 1=1 which will always be true, and then use AND as a prefix instead of a suffix.
$sqlSearch = "SELECT * FROM seafarers WHERE 1=1 ";
if ($dateS != "") {
$sqlSearch .= " AND add_date = '" . changeDateSlashToHypen($dateS) . "'";
}
...
But as pointed out in the other answer you need to use prepared statements. So, assuming you're using mysqli, which everyone seems to do for some reason:
$sqlSearch = "SELECT * FROM seafarers WHERE 1=1 ";
$types = "";
$parameters = [];
if ($dateS != "") {
$sqlSearch .= " AND add_date = ?";
$types .= "s";
$parameters[] = changeDateSlashToHypen($dateS);
}
if ($cdcS != "") {
$sqlSearch .= " AND cdc = ?";
$types .= "s";
$parameters[] = $cdcS;
}
if ($ppS != "") {
$sqlSearch .= " AND passport LIKE ?";
$types .= "s";
$parameters[] = "%$ppS%";
}
if ($surnameS != "") {
$sqlSearch .= " AND surname LIKE ?";
$types .= "s";
$parameters[] = "$surnameS%";
}
$stmt = $db->prepare($sqlSearch);
if (count($parameters) {
$stmt->bind_param($types, ...$parameters);
}
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
...
}

PHP : Multiple Textform Search

So , i got a form to search for jobseeker through the database . The form contain name , identity card , job position , academic certificate , age etc . The problem that i'm facing is when i'm searching for jobseeker based only on one text form for example , job position , the result is shown . But , if i want to search for jobseeker based on job position and academic level , the result is shown based on job position only . Is there anything wrong with my code ? need help here .. sorry for my bad english though ..
for job position :
$jawatan_arr = explode(',', $_POST['txt_jawatan']);
$jum_jawatan = count($jawatan_arr);
//echo "jum_didik = ".$jum_didik;
if($jum_jawatan > 0){
$d = 0;
foreach ($jawatan_arr as $value){
$d++;
//echo "; value::: ".$value." :::";
if($d == 1){
if($value != ''){
if($str == ''){
$str = " WHERE ";
}
else{
$str .= " AND ";
}
$str_jawatan .= " (LOWER(jawatan) LIKE '%".strtolower(rtrim(ltrim($value)))."%' ";
}
}
else{
if($value != ''){
$str_jawatan .= " OR LOWER(jawatan) LIKE '%".strtolower(rtrim(ltrim($value)))."%' ";
}
}
}
if($str_jawatan != ''){
$str_jawatan .= ") ";
$sql = "SELECT no_kp FROM jobseeker_pengalaman ".$str_jawatan;
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)){
if($row['no_kp'] != ''){
if(!in_array($row['no_kp'], $senarai_kp)){
array_push($senarai_kp, $row['no_kp']);
}
}
}
}
}
for academic level(checkbox , not a textform) :
$didik_arr = explode(',', $_POST['txt_taraf_pendidikan']);
$jum_didik = count($didik_arr) - 1;
//echo "jum_didik = ".$jum_didik;
if($jum_didik > 0){
$d = 0;
foreach ($didik_arr as $value){
$d++;
//echo "; value::: ".$value." :::";
if($d == 1){
if($str == ''){
$str = " WHERE ";
}
else{
$str .= " AND ";
}
$temp_didik .= $value;
}
else{
if($value != ''){
$temp_didik .= ",".$value;
}
}
}
//$str_didik .= " id_taraf_pendidikan IN (".$temp_didik.")";
$sql = "SELECT no_kp FROM jobseeker_pendidikan WHERE id_taraf_pendidikan IN (".$temp_didik.")";
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)){
if($row['no_kp'] != ''){
if(!in_array($row['no_kp'], $senarai_kp)){
array_push($senarai_kp, $row['no_kp']);
}
}
}
}
Do i need to join the my table ? because the job position is based on recent job experience , and academic is based on their study . Both of them are from different table
May be you can try IN statement? Something like this:
$sql = "SELECT no_kp FROM jobseeker_pengalaman ".$str_jawatan." IN
(
SELECT no_kp FROM jobseeker_pendidikan WHERE id_taraf_pendidikan IN (".$temp_didik.")
)";
So you will search by job positions within that jobseekers that already passed through your academic based search. I hope this approach will help.

making a better search query in php and mysql

I'm trying to create a search query:
I'm giving 6 options to search.
Bedrooms
Type
Postcode
Location
Min price
Max price
I have these fields in a form. I searched a lot but couldn't find the answer I was searching. I tried queries using LIKE and % too. But that didn't worked out too.
If a user selects only 'Type' then all of the data with that type should be displayed. And the same goes to other fields.
And again, if a user selects 2 or 3 options and searches then the results which match the options selected should be displayed.
How can I create a search like this? Should I do?:
if(){
}else if(){
}
You can build your sql query on the fly. If search value is not empty (or something else that does not count as a search value) then do not add search.
Do not forget to add mysql_real_escape_string to a params or bad people will exploit your software.
exampe in php:
<?php
$params = array('type' => 'aaa', 'max_price'=>100); // parameters that a user gave. Example from $_POST or $_GET
$querySearch = array();
if(isset($params['type'])) {
$querySearch[] = "type LIKE '%".mysql_real_escape_string($params['type'])."%'";
}
if(isset($params['max_price'])) {
$querySearch[] = "price <= ".mysql_real_escape_string($params['max_price']);
}
if(isset($params['min_price'])) {
$querySearch[] = "price >= ".mysql_real_escape_string($params['min_price']);
}
// and etc.
$q = 'select * FROM hotel WHERE ' . implode(' AND ' , $querySearch);
echo $q;
?>
then you can use query $q to do db select.
dynamically build the query
$useAnd = false;
$ query = " select * from table";
if (isset($bedrooms) == true or isset($type) == true or isset($postcode)==true or ...)
{
$query = $query. " where ";
if (isset($bedroomsIsset) = true)
{
$query = $query . "bedrooms >=". $bedrooms; $useAnd=true;
}
if (isset($type) = true)
{
if ($useAnd=true)
{$query = $query . " and " ;}
$query = $query . "type =". $type; $useAnd=true;
}
if (isset($postcode)==true)
{
if (isset($poscode) = true)
{
if ($useAnd=true)
{$query = $query . " and " ;}
$query = $query . "postcode =". $postcode; $useAnd=true;
}
if (...)
}
if(!empty($some_option)) $search_options["option_name"] = $some_option;
$query = "some query";
$where = "";
if(!empty($search_options)){
$first_option = array_shift($search_types);
$where = " " . key($first_option) . " = " . $first_option;
foreach($search_options as $key => $option){
$where .= " AND $key = $option";
}
}
$query .= $where;

Trouble pulling data out of an sql table

I have a html form tat my user can use to search through a table in my MYSQL database.
By default if you just hit go it will display the entire table, however I would like them to be able select certain fields and my php form to search via the fields that are filled in.
I seem to be unable to find a way of doing this without writing a seperate query for all 11 inputs in the different combinations they could be entered in, which comes out at a total of 76 queries..
If anyone has a way to simplify this I would love any advice.
I have tried just running a query with the AND operator but that doesnt work as some variables can be left empty and that will return no result, not sure if that is what is upposed to happen, but that is what is happening.
my html and php:
http://jsbin.com/oquwid/1/edit
PHP
$sql = "SELECT * FROM ".$tbl_name."
WHERE fname='".$fname."'
and lname='".$lname."'
and city='".$city."'
and phone='".$pohne."'
and interest_inet='".$internet."'
and interest_tv='".$television."'
and interest_voice='".$voice."'
and submission_ip='".$ip."'
and inquiry_handled='".$handled."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
echo $row;
}
echo "</table>";
You could append parts to the query depending on which are filled in:
if(!empty($fname) || !empty($lname) || !empty($city) || etc.etc.) {
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryParts = array();
if($fname != "") {
$queryParts[] = " fname='$fname'";
}
if($lname != "") {
$queryParts[] = " lname='$lname'";
}
etc.etc.
$sql .= implode(" AND ", $queryParts);
// do query, etc.
}
else {
// Don't do query if no parameters are specified
}
You also need to make sure that you escape all of your query parameters before you use them or risk having someone ravage your data.
The following uses loops to avoid duplicate code:
$fieldIsSpecified = false;
$queryFields = array('fname' => $fname, 'lname' => $lname, 'city' => $city, etc...);
foreach($queryFields as $column => $value) {
if(!empty($value){
$fieldIsSpecified = true;
break;
}
}
if($fieldIsSpecified) {
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryParts = array();
foreach($queryFields as $column => $value) {
if(!empty($value)) {
$queryParts[] = " $column = '$value'";
}
}
$sql .= implode(" AND ", $queryParts);
// do query, etc.
}
else {
// Don't do query if no parameters are specified
}
The reason you're query isn't working if a value is not filled in, is probably because the query results in this (given first name is empty)
SELECT * FROM $tbl_name WHERE fname=''
And there probably isn't a user having no first name.
Further, you considered adding a flag per requested info, and on base of that either add or remove the needed part to the select part of the query ?
For example,
$sql = "SELECT * FROM $tbl_name WHERE ";
$queryChanged = false;
if (isset($fname)){
if (!empty($fname)){
$sql .= "fname='$fname' ";
$queryChanged=true;
}
}
if (isset($lname)){
if (!empty($lname)){
$sql .= ($queryChanged) ? " AND lname='$lname'" : "lname='$lname'";
$queryChanged = true;
}
}
... //Continue the logic
I'd recommend you to read this post about select * as well as this about user input and how to handle it
this is how i am going to have to do it
php:`
//if just lname is set
if(empty($start_date) && empty($end_date) && empty($fname) && isset($lname) && empty($city) &&
empty($internet) && empty($television) && empty($voice) && empty($phone) && empty($ip) &&
empty($handled) && empty($not_handled)){
$sql = "SELECT * FROM ".$tbl_name."
WHERE lname='".$lname."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
}
echo "</table>";
exit();
}
//if just city is selected
if(empty($start_date) && empty($end_date) && empty($fname) && empty($lname) && isset($city) &&
empty($internet) && empty($television) && empty($voice) && empty($phone) && empty($ip) &&
empty($handled) && empty($not_handled)){
$sql = "SELECT * FROM ".$tbl_name."
WHERE city='".$city."'";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
}
echo "</table>";
exit();
}
And etc... i am going to have to repeat this process until i cover all, 76 i believe, possibilites. thnkfully its just a lot of copy paste. thanks for the help everyone
First don't use MYSQL_*. Use PDO
Second, with your code, your are requiring all fields to be filled.
If you don't wanna do that then go this way:
You can use WHERE 1=1 , but it's not recommended !!!!!
$sql = "SELECT * FROM ".$tbl_name." WHERE confirm = '0' ";
$sql .= "AND fname = ".$fname."";
$sql .= "AND lname = ".$lname."";
$sql .= "AND city = ".$city."";
$sql .= "AND phone = ".$pohne."";
$sql .= "ORDER BY date DESC";
$result = mysql_query($sql);
echo "<table border='1'>";
echo "<tr>";
$i = 0;
while ($i < mysql_num_fields($result))
{
$meta = mysql_fetch_field($result, $i);
echo "<th>".$meta->name."</th>";
$i++;
}
while ($row = mysql_fetch_row($result))
{
echo '<tr>';
foreach($row as $item)
{
echo "<td>".$item."</td>";
}
echo '</tr>';
echo $row;
}
echo "</table>";

PHP navigation with filters

I am working out a faceted navigation (I think that's the right expression...)
So I have a lot of categories and manufacturers on which a user can filter.
I came to the point where I have to get the results from the filters from my database. What would the fastest way to create these queries? I have 3 get values that I can filter on (manufacturer/company/category) so that would mean i would write a query for when manufacturer & company is an active filter and for category and company etc... I see how much work this is and I wonder if there is a short way to do this?
probably want something like below (if I understand your question correctly:
SELECT * FROM tablename WHERE manufacturer='A' AND company='B' AND category='C'
If you're using PHP, you could use it to put the current value in for A, B, and C - but remember to sanitize these values
Edit
For example, with PHP...
<?php
$manufacturer = mysql_real_escape_string($_GET['manufacturer']);
$company = mysql_real_escape_string($_GET['company']);
$category = mysql_real_escape_string($_GET['category']);
$query = "SELECT * FROM tablename WHERE manufacturer='".$manufacturer."' AND company='".$company."' AND category='".$category."'";
// then simply run the query....
?>
Edit 2
You can change AND to OR when needed be
<?php
$query = "SELECT * FROM tablename";
$mixed_query = "";
if(isset($_GET['manufacturer']) && !empty($_GET['manufacturer'])){
$mixed_query .= ($mixed_query !== "") ? " AND " : " WHERE ";
$mixed_query .= "manufacturer='".mysql_real_escape_string($_GET['manufacturer'])."'";
}
if(isset($_GET['company']) && !empty($_GET['company'])){
$mixed_query .= ($mixed_query !== "") ? " AND " : " WHERE ";
$mixed_query .= "company='".mysql_real_escape_string($_GET['company'])."'";
}
if(isset($_GET['category']) && !empty($_GET['category'])){
$mixed_query .= ($mixed_query !== "") ? " AND " : " WHERE ";
$mixed_query .= "category='".mysql_real_escape_string($_GET['category'])."'";
}
// then add to query
$query .= $mixed_query;
// then simply run the query....
?>
The simplest solution would probably be one where you build the query dynamically:
// GET SANITIZED $manufacturer $company $category
// Initialize the array
$facets = array();
if (isset($manufacturer))
{
$facets[] = "manufacturer = '$manufacturer'";
}
if (isset($company))
{
$facets[] = "company = '$company'";
}
if (isset($category))
{
$facets[] = "category = '$category'";
}
$query = "SELECT * FROM table";
if (count($facets) > 0)
{
$query .= " WHERE" . implode(" AND ", $facets);
}
Your query would only filter on those facets that are set.
To make it slightly more general:
// GET SANITIZED $manufacturer $company $category
// Initialize the array
$facets["manufacturer"] = $manufacturer;
$facets["company"] = $company;
$facets["category"] = $category;
// ADD MORE AS NECESSARY
foreach($facets as $key=>$value)
{
if ($value != '')
{
$where[] = "$key = '$value'";
}
}
$query = "SELECT * FROM table";
if (count($where) > 0)
{
$query .= " WHERE" . implode(" AND ", $where);
}

Categories