how to get multipale search input php mysql - php

hi i am new to php mysql. I have created a form where the user can search the database, and the result depends on how the user fills in the form. form has 6 search fields. where user can choose / fill any of one or more fields to make his search. i have coded it as follows
php
<?php require_once('Connections/osrc.php'); ?>
<?php
$maxRows_search_result = 10;
$pageNum_search_result = 0;
if (isset($_GET['pageNum_search_result'])) {
$pageNum_search_result = $_GET['pageNum_search_result'];
}
$startRow_search_result = $pageNum_search_result * $maxRows_search_result;
mysql_select_db($database_osrc, $osrc);
$propertyid = $_POST['propertyid'];
$offered = $_POST['offered'];
$property_type = $_POST['property_type'];
$beds = $_POST['beds'];
$city = $_POST['city'];
$locality = $_POST['locality'];
$query_search_result = "SELECT * FROM osrc_data WHERE propertyid LIKE '%$propertyid%' OR offered LIKE '%$offered%' AND property_type LIKE '%$property_type%' AND beds LIKE '%$beds%' AND city LIKE '%$city%' AND locality LIKE '%$locality%' ";
$query_limit_search_result = sprintf("%s LIMIT %d, %d", $query_search_result, $startRow_search_result, $maxRows_search_result);
$search_result = mysql_query($query_limit_search_result, $osrc) or die(mysql_error());
$row_search_result = mysql_fetch_assoc($search_result);
if (isset($_GET['totalRows_search_result'])) {
$totalRows_search_result = $_GET['totalRows_search_result'];
} else {
$all_search_result = mysql_query($query_search_result);
$totalRows_search_result = mysql_num_rows($all_search_result);
}
$totalPages_search_result = ceil($totalRows_search_result/$maxRows_search_result)-1;
?>
now when user It works but it shows all rows in database table.
for example user fills up three fields beds, city, locality and rest of three are blank.
search result page shows all rows in data base with all records.
pls help me to correct my codes. Thanks in advance

First, I agree with #VaaChar, you should be using mysqli or even better yet PDO.
You will have determine IF a value has been placed in a field and if so use it in your query. If no value was placed in the field ignore it in your query.
Something like this...
$sqlid = "";
$sqloffered = "";
$sqltype = "";
$sqlbeds = "";
$sqlcity = "";
$sqllocality = "";
if(isset($propertyid)) {
$sqlid = " propertyid LIKE '%$propertyid%'";
}
if(isset($propertyid) && isset($offered)) {
$sqloffered = " OR offered LIKE '%$offered%'";
}
if(!isset($propertyid) && isset($offered)) {
$sqloffered = " offered LIKE '%$offered%'";
}
if(isset($property_type)) {
$sqltype = " AND property_type LIKE '%$property_type%'";
}
if(isset($beds)) {
$sqlbeds = " AND beds LIKE '%$beds%'";
}
if(isset($city)) {
$sqlcity = " AND city LIKE '%$city%'";
}
if(isset($locality)) {
$sqllocality = " AND locality LIKE '%$locality%'";
}
$sql = "SELECT * FROM osrc_data WHERE {$sqlid}{$sqloffered}{$sqltype}{$sqlbeds}{$sqlcity}{$sqllocality} ";

When you build the sql query with (say) $propertyid empty, you get this :
.... LIKE '%%' ...,
which is like saying "anything". You must build your query only with the fields that have been filled.

Related

Update multiple rows in single query php mysql

I am trying to update multiple rows in a single query. Data doesnt get updated in my code. I am trying to join the two tables. When user enters a no. The data from the 2 tables will be displayed which is connected through the foreign key.The data from the table1 gets updated. Where as the columns from the table 2 doesnt get updated. I need to update the second table based on unique id
if($_REQUEST["profile"] == "profile")
{
$Id = $_REQUEST["id"];
$firstname = mysql_real_escape_string($_REQUEST["firstname"]);
$serial = mysql_real_escape_string($_REQUEST["serial"]);
$dom = mysql_real_escape_string($_REQUEST["dom"]);
$idno = $_REQUEST["idno"];
$pow = mysql_real_escape_string(stripslashes($_REQUEST["pow"]));
$address = mysql_real_escape_string(stripslashes($_REQUEST["address"]));
$bookno = mysql_real_escape_string(stripslashes($_REQUEST["bookno"]));
$zone = mysql_real_escape_string(stripslashes($_REQUEST["zone"]));
$mobile = mysql_real_escape_string(stripslashes($_REQUEST["phone"]));
$phone = mysql_real_escape_string(stripslashes($_REQUEST["mobile"]));
$mothertongue=mysql_real_escape_string(stripslashes($_REQUEST["mothertongue"]));
$nof=mysql_real_escape_string(stripslashes($_REQUEST["nof"]));
$email=mysql_real_escape_string(stripslashes($_REQUEST["email"]));
$nom=$_REQUEST["nom"];
$nofemale=$_REQUEST["nofemale"];
mysql_query("UPDATE profile SET firstname='".$firstname."',serial='".$serial."',dom='".$dom."',idno='".$idno."',pow='".$pow."',address='".$address."',bookno='".$bookno."',
zone='".$zone."',phone='".$mobile."',mobile='".$phone."',mothertongue='".$mothertongue."',email='".$email."',nof='".$nof."',nom='".$nom."',nofemale='".$nofemale."' WHERE id = '".$_POST['id']."' " ) or die(mysql_error());
for($i=0;$i<count($_REQUEST['slno1']);$i++)
{
$mid=$_REQUEST['mid'][$i];
$slno1 = mysql_real_escape_string(stripslashes($_REQUEST["slno1"][$i]));
$name1 = mysql_real_escape_string(stripslashes($_REQUEST["name1"][$i]));
$rhof1 = mysql_real_escape_string(stripslashes($_REQUEST["rhof1"][$i]));
$dob1 = mysql_real_escape_string(stripslashes($_REQUEST["dob1"][$i]));
$dobapt1 = mysql_real_escape_string(stripslashes($_REQUEST["dobapt1"][$i]));
$doc1 = mysql_real_escape_string(stripslashes($_REQUEST["doc1"][$i]));
$doconf1 = mysql_real_escape_string(stripslashes($_REQUEST["doconf1"][$i]));
$qualification1 = mysql_real_escape_string(stripslashes($_REQUEST["qualification1"][$i]));
$school1 = mysql_real_escape_string(stripslashes($_REQUEST["school1"][$i]));
$occupation1 = mysql_real_escape_string(stripslashes($_REQUEST["occupation1"][$i]));
$run=mysql_query("UPDATE member SET
slno1='".$slno1."',name1='".$name1."',rhof1='".$rhof1."',dob1='".$dob1."',dobapt1='".$dobapt1."',doc1='".$doc1."',doconf1='".$doconf1."',qualification1='".$qualification1."' WHERE mid = '".$mid."' " ) or die(mysql_error());
}
}
Please use PDO so you won't have to escape strings and so your code gets simpler to read. Your query has too many quotes used and this alone can make it easy to fail. Please use following examples and this should help you succeed.
Basic PDO update:
https://www.w3schools.com/php/php_mysql_update.asp
Bind Params:
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
In your query you are using $_POST['mid'] instead of that you should use $mid which you are already reading as
$mid=$_REQUEST['mid'][$i];
As per my understanding UPDATE query is used to update a limited number of records if using the where condition. So the only way that I can think of is using an INSERT query with ON DUPLICATE KEY UPDATE clause. Try the below code:
for($i=0;$i<count($_REQUEST['mid']);$i++) {
$mid[] = $_REQUEST['mid'][$i];
$slno1[] = mysql_real_escape_string(stripslashes($_REQUEST["slno1"][$i]));
$name1[] = mysql_real_escape_string(stripslashes($_REQUEST["name1"][$i]));
$rhof1[] = mysql_real_escape_string(stripslashes($_REQUEST["rhof1"][$i]));
$dob1[] = mysql_real_escape_string(stripslashes($_REQUEST["dob1"][$i]));
$dobapt1[] = mysql_real_escape_string(stripslashes($_REQUEST["dobapt1"][$i]));
$doc1[] = mysql_real_escape_string(stripslashes($_REQUEST["doc1"][$i]));
$doconf1[] = mysql_real_escape_string(stripslashes($_REQUEST["doconf1"][$i]));
$qualification1[] = mysql_real_escape_string(stripslashes($_REQUEST["qualification1"][$i]));
$school1[] = mysql_real_escape_string(stripslashes($_REQUEST["school1"][$i]));
$occupation1[] = mysql_real_escape_string(stripslashes($_REQUEST["occupation1"][$i]));
}
$query = "INSERT INTO `member` (`mid`,`slno1`,`name1`,`rhof1`,`dob1`,`dobapt1`,`doc1`,`doconf1`,`qualification1`) VALUES ";
for ($i = 0; $i < count($mid); $i++) {
$query .= "('".$mid[$i]."','".$slno1[$i]."','".$name1[$i]."','".$rhof1[$i]."','".$dob1[$i]."','".$dobapt1[$i]."','".$doc1[$i]."','".$doconf1[$i]."','".$qualification1[$i]."')";
if ($i != (count($mid) - 1)) {
$query .= ',';
}
}
$query .= ' ON DUPLICATE KEY UPDATE `slno1` = VALUES(`slno1`), `name1` = VALUES(`name1`), `rhof1` = VALUES(`rhof1`), `dob1` = VALUES(`dob1`), `dobapt1` = VALUES(`dobapt1`), `doc1` = VALUES(`doc1`), `doconf1` = VALUES(`doconf1`), `qualification1` = VALUES(`qualification1`);';
$run=mysql_query($query) or die(mysql_error());
Hope This Helps.

SQL Query for filter panel not working good

Hey I was making a college internship portal project using PHP but getting stuck at this point where for all relevant and irrelevant details from the filter table the page is showing results!
The filter table asks following details regarding:
1. Category - where the category of internship is to be provided
2. Location - the location where he desires to do the internship
3. The starting date
4. Work from home or not
5. fifth is a specific keyword search to find all relevant data related to the keyword
PHP code is
<?php
if (isset($_POST['search']))
{
$category = trim($_POST['cat']);
$location = trim($_POST['loc']);
$start = $_POST['start-date'];
$starting = strtotime($start);
$duration = $_POST['duration'];
$work = '';
$key = $_POST['key-srch'];
if (isset($_POST['work-home']))
{
$work = $_POST['work-home'];
}
elseif (!empty($duration))
{
if (!is_numeric($duration))
{
$err_msg = "Please enter a number upto 6 !";
$code = '1';
}
}
else
{
$sql = " SELECT *
FROM is_internship
WHERE
(`profile/category` LIKE '$category' OR `location` LIKE '$location' OR `start_date` >= '$starting')
OR (`duration` LIKE '$duration' OR `job-type` LIKE '$work')
OR (`profile/category` LIKE '%{$key}%' OR `job-type` LIKE '%{$key}%'
OR `part-time` LIKE '%{$key}%'
OR `location` LIKE '%{$key}%' )";
$query = mysqli_query($con,$sql);
if ($query == TRUE && mysqli_num_rows($query) > 0)
{
echo mysqli_num_rows($query);
$data = mysqli_fetch_array($query,MYSQLI_BOTH);
}
}
}
?>
The whole code works well except the sql query which i suppose to be wrong at this point of time... Thanks in advance!!

PHP Additional if statements block first one

I have following statements:
if (isset($_POST['name'])) {
$name = $_POST['name'];
$sql = "SELECT * FROM patients WHERE name LIKE '{$name}' ";
} elseif (isset($_POST['surname'])) {
$surname = $_POST['surname'];
$sql = "SELECT * FROM patients WHERE surname LIKE '{$surname}' ";
} elseif (isset($_POST['pesel'])) {
$pesel = $_POST['pesel'];
$sql = "SELECT * FROM patients WHERE pesel LIKE '{$pesel}' ";
}
And I have 3 search forms. But only the first one works (name). Other do not respond. How to change it?
Please check if all the $_POST[] variables are not set at the same time. Because, $_POST['name'] is the first variable and if it is set, other conditions will not be checked.
The browser will send the input field in the request, even if it's empty.
You cannot test whether a string is empty with isset. You need !== "" too.
try this....
if(isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
$sql = "SELECT * FROM patients WHERE name LIKE '{$name}' ";
}
else if(isset($_POST['surname'])) {
$surname = $_POST['surname'];
echo $surname;
$sql = "SELECT * FROM patients WHERE surname LIKE '{$surname}' ";
}
else if(isset($_POST['pesel'])) {
$pesel = $_POST['pesel'];
echo $pesel;
$sql = "SELECT * FROM patients WHERE pesel LIKE '{$pesel}' ";
}
You can use multiple like condition in single query
$sql = "SELECT * FROM patients WHERE name LIKE '{$name}' OR LIKE '{$surname}' OR LIKE '{$pesel}' ";
try this:
if(isset($_POST['name'])||isset($_POST['surname'])||isset($_POST['pesel'])) {
$name = $_POST['name'];
$sql = "SELECT * FROM patients WHERE name LIKE '{$name}' or surname LIKE '{$surname}' or pesel LIKE '{$pesel}'";
}

Dynamic PHP Query - Filter Selection

Ok Guys i need your Help One More Time Please if you can??
I have a list of drop down options as a set of filter criteria.
When each is selected, it adds it to a query string and appends an equals (=) to the selection, so if i select Large, the query would be where size = large.
I have one selection called impacted, but when a user selects impacted, i dont want the query to append = to, i want it to become where impacted LIKE 'click', so that it will search anywhere in the database column impacted.
If it remains at = to, it will only bring back a selection where there is only ONE impacted system that is stored against a lesson exactly = to the selection.
SELECT p.project_id
, p.project_name
, p.department
, p.size
, p.programme
, l.captured_by
, l.stage
, l.type
, l.impacted
, l.depts_inv
, l.lesson_title
, l.lesson_learned
, l.lesson_added
FROM ll_project p
JOIN ll_lessons l
ON l.project_id = p.project_id
AND l.impacted = 'Click';
This is how it currently pulls the code in but if someone has made a selection against the impacted filter i want the query not to add = before it but 'contains' or 'like' if you know what i mean.
Here is the full code.
<?php
//Set all Variables pulled from POST of previous page
$pid = $_POST['project_id'] ;
$psize = $_POST['projectSize'] ;
$pdepts = $_POST['depts'] ;
$lstage = $_POST['stage'] ;
$ltype = $_POST['type'] ;
$impacted = $_POST['impacted'] ;
//Create Column Variable to hold Values in an array linked to the database columns
$columns = array('project_id'=>'ll_project.project_id','projectSize'=>'size','depts'=>'department','stage'=>'ll_lessons.stage','type'=>'ll_lessons.type','impacted'=>'ll_lessons.impacted');
$sqlString = null;
//Check all POSTED data is pulling through - Should be 6
//echo "Total Number Of Captured Post Variables is:";
//echo count($_POST);
$number = 0;
$queryStr = "";
$preStr = array();
//For Every POSTED Value Set the Name as Key and the Value against Each
foreach ($_POST as $key => $val ) {
if (!empty($_POST[$key])){
if(!is_array($_POST[$key]))
//Escape the VALUE by surrounding it with Quotes as it is a string the value would not be picked up on the query.
$currentStr = $columns[$key]." = '".mysql_real_escape_string($val)."'";
else
$currentStr = $columns[$key]." IN (".implode(',',$_POST[$key]).")";
$preStr[] = $currentStr;
}
}
//set the Query String that i want to return from the Database and set the join on the BSKYB NUMBERS on both Tables
$queryStr = "SELECT ll_project.project_id, ll_project.project_name, ll_project.department, ll_project.size, ll_project.programme, ll_lessons.captured_by, ll_lessons.stage, ll_lessons.type, ll_lessons.impacted, ll_lessons.depts_inv, ll_lessons.lesson_title, ll_lessons.lesson_learned, ll_lessons.lesson_added FROM ll_project INNER JOIN ll_lessons ON ll_project.project_id = ll_lessons.project_id WHERE ".implode(' AND ',$preStr);
The answer is so!
if ($key == 'impacted') {
$currentStr = $columns[$key] . " LIKE '%" . mysql_real_escape_string($val) . "%'";
} else {
$currentStr = $columns[$key] . " = '" . mysql_real_escape_string($val) . "'";
}
else
$currentStr = $columns[$key]." IN (".implode(',',$_POST[$key]).")";
$preStr[] = $currentStr;
}
}
Thanks for checking it out Strawberry :)

MySQL Query not calling data based on variable

Im trying to call all users from a database with the same interests as the current, logged in user on my website.
I have the following
// Get Session USER interest
$interestsquery = "SELECT `interest` FROM `user_interests` WHERE `user_id` = " . $usersClass->userID();
$result = mysql_query($interestsquery);
$interests = array();
while(list($interest) = mysql_fetch_array($result))
$interests[] = $interest;
$interest1 = $interests['1'];
$interest2 = $interests['2'];
$interest3 = $interests['0'];
// END INTERESTS
//USers with Same Interests
$interests_query = "SELECT * FROM produgg_users
join user_interests on produgg_users.id = user_interests.user_id
where interest = '$interest1' and produgg_users.id != '".$usersClass->userID()."'";
$interests_result = mysql_query($interests_query) or die(mysql_error());
if($interests_result != 0) {
while($interests_row = mysql_fetch_array($interests_result, MYSQL_ASSOC))
{
echo $interests_row['user_id'];
}
}
else
{
print "No users to display!";
}
//END SAME INTERESTS
which doesnt bring back any data, yet if I add (beneath //USers with Same Interests)
$interest1 = 'footy';
the interests_query seems to work, can anybody see where im going wrong?
My problem seems to lie here...
$interest1 = $interests['1'];
$interest2 = $interests['2'];
$interest3 = $interests['0'];
// END INTERESTS
//USers with Same Interests
$interest1 = 'footy';
If I manually assign a value to $interest variable it works, but i need to get use the value from the array above, does this make sense?
If your code brings back the correct data when you add $interest1 = 'footy'; line, that would imply that there is something wrong with the value of that variable when you don't. Have you tried var_dump($interest1); right under //Users with Same Interests line to see what kind of input you get from your interestsquery?
I would expect the var_dump to not return a valid string (since if it would, the query would work following the $interest1 = 'footy'; assumption), so you would have to look at what interestsquery returns wrong.
Looks like you querying user_id from user_interests as number, but from produgg_users as string. Maybe there's a problem
You can do it with one query:
$userID = mysql_real_escape_string($usersClass->userID());
$sql = "
SELECT * FROM user_interests AS ui1
JOIN LEFT user_interests AS ui2 ON ui1.id = ui2.id
JOIN LEFT produgg_users AS pu ON ui2.user_id = pu.id
WHERE ui.user_id = " . userID ;

Categories