PHP : Multiple Textform Search - php

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.

Related

PHP MySQL Advance Search with Check boxes

I am trying to build search logic that uses multiple form fields and adjusts the MySQL search accordingly. My main area of issue is when dealing with multiple checkboxes. The below gets me close but I get multiple "OR" at the end for some reason. The below gives me (nema = '1' OR OR nema = '12' OR OR nema = '4' OR OR ) for example. More OR's are added for each checkbox. What am I missing or not doing correctly?
$rating = mysqli_real_escape_string($db, implode(',', $_POST['rating']));
$q = "SELECT * FROM lekker WHERE height BETWEEN 20 AND 30 ";
if (!empty($rating)) {
$var = explode(',',$rating);
$rating_count = count($var);
if($rating_count > 1) {
$q .= "AND (";
foreach($var as $test) {
$q .= "nema = '$test'";
for($i=0;$i<$rating_count;$i++) {
if($i!=$rating_count-1) {
$q .= " OR ";
}
}
}
$q .= " )";
} else {
$q .= "nema = '$rating'";
}
}
$q .= " ORDER BY `part` ASC";
This is the Select I am trying to achieve:
SELECT * FROM lekker WHERE height BETWEEN 20 AND 22 AND (nema = '1' OR nema = '12') ORDER BY part ASC
I removed the second loop and always add OR, then you can remove the last one at the end
$rating = mysqli_real_escape_string($db, implode(',', $_POST['rating']));
$q = "SELECT * FROM lekker WHERE height BETWEEN 20 AND 30 ";
if (!empty($rating)) {
$var = explode(',',$rating);
$rating_count = count($var);
if($rating_count > 1) {
$q .= "AND (";
foreach($var as $test) {
$q .= "nema = '$test' OR ";
}
$q=substr($q, 0,-4);
$q .= " )";
} else {
$q .= "nema = '$rating'";
}
}
$q .= " ORDER BY `part` ASC";
Instead of worrying about whether or not you need to add an OR simply add it each time through your foreach then trim off the trailing OR after you are done with the foreach.
if ($rating_count > 1) {
$q .= "AND (";
foreach($var as $test) {
$q .= "nema = '$test' OR ";
}
$q .= rtrim($q,' OR ') . ' )';
} else {
$q .= "nema = '$rating'";
}

PHP advanced search with Multiple OPTION

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) : '';

Displaying MySQL results in two columns (editing existing code)

I have been asked to revise an existing site, it's still using PHP5.3 and an old version of PHPmyDirectory, and the code is a little messy.
I'm trying to revise it to just display the list of cities in two columns. I'm trying to do it as a table, as it seemed easiest, but I could also just pull the results into to side by side divs, as there are never more than 26 cities listed (so first half or first 13 in div one, the rest in div two).
Here's the existing original code (I know its not mysqli, but we'll be redoing this site shortly so there's no sense trying to redo a million pages of code right now):
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
return $output;
}
This is what is looks like currently: Current Site
Here's what I've tried to do:
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
$result_array = array();
while ($service = fetch_array($result)) {
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2) {
break;
}
else {
while ($service2 = fetch_array($result2)) {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
echo "<table>";
for ($j=0; $j<$i; $j=$j+2) {
echo "<tr>";
echo "<td>".$title_array[$j]."</td><td>".$title_array[$j+1]."</td>";
echo "</tr>";
}
echo "</table>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<p><b>".$title." will travel for an additional fee!</b></p>";
}
else {
$output .="";
}
}
return $output;
}
And here's what I'm getting: DEV site
I'm very much a PHP newbie, and my understanding is pretty spotty, but I've tried a bunch of different solutions I've found here, and can't get them to work. I'm sure I'm missing something obvious.
Thanks for any pointers!
if I got it correct you should change your
else {
$output = "<p>";
$result_array = array();
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
while ($service2 = fetch_array($result2))
{
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
$output .= "<br/>";
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
$output .="</p>";
}
}
with
else {
$output = "<table>";
$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "";
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<tr><td>'."{$service2['title']}".'</td>';
$even_odd=false;
} else {
$output .= '<td>'."{$service2['title']}".'</td></tr>';
$even_odd=true;
}
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<b>".$title." will travel for an additional fee!</b></p>";
} else {
if (!$even_odd)$output .="<td></td></tr>";
$output .="</table>";
}
}
Try this, I couldn't test it of course, since I've got no access to the data being loaded.
echo "<table>";
$result_array = array();
while ($service = fetch_array($result))
{
//this will loop multiple times. 7 times for Tony S. in the example.
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
$i=0;
if(!$result2)
{
break;
}
else
{
while ($service2 = fetch_array($result2))
{
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
$i++;
}
}
}
for ($j=0; $j < count($result_array); $j++)
{
if ($j % 2 == 0)
{
echo "<tr>";
}
echo "<td>".$result_array[$j][0]." (".$result_array[$j][1].")</td>";
if ($j % 2 == 0)
{
echo "</tr>";
}
if ($j % 2 == 1 && $j == count($result_array)-1)
{
echo "<td></td></tr>";
}
}
echo "</table>";
Paste and replace between this lines:
if(!$result){
$output = "<p>Call for Service Area!</p>";
}
else {
.... PASTE IN HERE ....
}
Building on Kim's code, I was able to get it working with some revisions. I also scrapped the table for divs, since it seems less messy to me and it seemed like the table styling was interfering somehow.
function create_service_area($title) {
global $listing;
$sql = "SELECT state_id, city_id FROM " .T_LISTINGS_CITIES. " WHERE listing_id = {$listing['id']} " ;
$result = query($sql);
if(!$result){
$output = "<p>Call for Service Area!</p>";
} else {
$output = "<div>";
//$result_array = array();
$even_odd=true;
while ($service = fetch_array($result))
{
$sql2 = "SELECT title FROM " .T_LOCATIONS. " WHERE id = {$service['city_id']} " ;
$result2 = query($sql2);
if(!$result2){
break;
} else {
$output .= "{$service2['title']}";
$title_array = explode(',', $service2['title']);
$result_array[] = $title_array;
while ($service2 = fetch_array($result2))
{
if ($even_odd) {
$output .= '<div style="float:left;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=false;
} else {
$output .= '<div style="float:right;width:50%;">'."{$service2['title']}".'</div>';
$even_odd=true;
}
}
}
}
if($listing['custom_103'] =="Yes") {
$output .= "<div style='clear:both;width:90%;float:none;'><p><b>".$title." will travel for an additional fee!</b></p></div>";
} else {
}
}
return $output;
}
Thanks so much Kim and Mouser!

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