MySQL/PHP: connecting two individual search forms - php

My situation:
I have two different forms. One common search form where users can search for products by their name/description, and another form that lets users search for products by their location (postcode and city).
This is the html for my search form:
<form name="searchform" method="post" action="index.php?go" class="searchform">
<input type="text" name="search" value="" placeholder="Suchen..." class="field_search" id="tags">
</form>
and this is the html for my location-search form:
<form class="location" method="post" action="index.php?go_location">
<input type="image" src="img/location/location.png" width="30" height="30" id="location_image" title="Ortung aktivieren"/>
<input type="text" size="18" placeholder="PLZ, Ort" name="location" id="location" title="Standort angeben"/>
<input type="image" name="" value="" src="img/location/go.png" width="30" height="30" id="location_submit"/>
</form>
and the corresponding php:
if(isset($_POST['search'])){
if(isset($_GET['go'])){
if(preg_match("/[A-Z | a-z]+/", $_POST['search'])){
$input=$_POST['search'];
$currently_searching = true;
//connect to db
$sql="SELECT * FROM table WHERE Name LIKE '%".$input."%' OR Description LIKE '%".$input."%'";
//echo results
}}}}
elseif(isset($_POST['location'])){
if(isset($_GET['go_location'])){
$input_location=$_POST['location'];
$currently_locationing = true;
$sql="SELECT * FROM table WHERE Postcode LIKE '%".$input_location."%' OR City LIKE '%".$input_location."%' OR Combined LIKE '%".$input_location."%' OR Combined2 LIKE '%".$input_location."%'";
//echo results
}}}
Now, individually, they work fine.
What I would like to achieve is connecting these two forms in a way that lets users who are already searching for a certain string (via the common search form) use the location - search form to narrow the results down to those corresponding with the given postcode...
I hope this is clear. I thought something like: If a user uses the common search form, the
$currently_searching
variable becomes "true", so if this variable is true and the user is using the location - search form, then connect them... so I tried adding something like this to the php-statement:
elseif(isset($_POST['location']) && $currently_searching == true){
if(isset($_GET['go_location']) && $currently_searching == true){
if($currently_searching == true){
$input_location=$_POST['location'];
$currently_locationing = true;
//connect to db
$sql="SELECT * FROM table WHERE (Name LIKE '%".$input."%' OR Description LIKE '%".$input."%') AND (Postcode LIKE '%".$input_location."%' OR City LIKE '%".$input_location."%' OR Combined LIKE '%".$input_location."%' OR Combined2 LIKE '%".$input_location."%')";
//echo results
}}}}
It doesn't work though. I'd appreciate some help guys! Thanks in advance.

Here is a little trick. Add the id locationForm to your location form and searchForm to your search form, so it looks like this:
<form id="locationForm" class="location" method="post" action="index.php?go">
<input type="image" src="img/location/location.png" width="30" height="30" id="location_image" title="Ortung aktivieren"/>
<input type="text" size="18" placeholder="PLZ, Ort" name="location" id="location" title="Standort angeben"/>
<input type="image" name="" value="" src="img/location/go.png" width="30" height="30" id="location_submit"/>
</form>
<form id="searchForm" name="searchform" method="post" action="index.php?go" class="searchform">
<input type="text" name="search" value="" placeholder="Suchen..." class="field_search" id="tags">
</form>
Then add this javascript:
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$(document).on('submit', '#locationForm, #searchForm',function(e){
var locationInput = $('#locationForm input[name="location"]').clone();
locationInput.attr('type','hidden');
var searchInput = $('#searchForm input[name="search"]').clone();
searchInput.attr('type','hidden');
$('#locationForm').prepend(searchInput);
$('#searchForm').prepend(locationInput);
});
</script>
The javascript will add the search field to the location form and visa versa before submitting. So whenever you submit one of the forms, you will always have both values.
EDIT
In your corresponding.php you could use something like this if there are two seperate queries needed.
if(isset($_POST['search']))
{
$sql="SELECT * FROM table WHERE Name LIKE '%".$input."%' OR Description LIKE '%".$input."%'";
//Execute query
//Fetch results
}
if(isset($_POST['location']))
{
$sql="SELECT * FROM table WHERE Postcode LIKE '%".$input_location."%' OR City LIKE '%".$input_location."%' OR Combined LIKE '%".$input_location."%' OR Combined2 LIKE '%".$input_location."%'";
//Execute query
//Fetch results
}
//Combine results of search and location query
//echo results
Or if it's possible to execute one query you can use this:
if(isset($_POST['search']) && isset($_POST['location']))
{
$sql="HERE YOUR QUERY WHERE YOU CAN USE $_POST['search'] AND $_POST['location']";
//Execute query
//Fetch results
}
//Combine results of search and location query
//echo results

Related

How to make search form where user has three columns to search.Using PHP AND SQL AND HTML

I was wondering how to make a search form where user has 3 options to search with
Search By age (dropdown 18-25 & 26-40)
Search By gender (male or female)
Search By name
In my code, when I click "Submit" with blank fields, it's throwing all data which i don't it to:
<?php
$output = NULL;
if (isset ( $_POST ['submit'] )) {
// Connect to database
$mysqli = new Mysqli ( "localhost", "root", "2222", "matrimonialPortal" );
$search = $mysqli->real_escape_string ( $_POST ['search'] );
// Query the databse
$resultSet = $mysqli->query ( "SELECT * FROM mp_user WHERE name LIKE '%$search%' OR email LIKE '%$search%' OR salutation LIKE '%$search%' OR id LIKE '%$search%'" );
if ($resultSet->num_rows > 0) {
while ( $rows = $resultSet->fetch_assoc () ) {
$name = $rows ['name'];
$email = $rows ['email'];
$output .= "::<strong>The Details of your search</strong> ::<br /> Name: $name<br /> Email:$email<br /><br /> ";
}
} else {
$output = "Oops No results Found!!";
}
}
?>
<!-- The HTML PART -->
<form method="POST">
<div>
<p>
Search By name: <input type="TEXT" name="search" /> <input
type="SUBMIT" name="submit" value="Search >>" />
</p>
</div>
<div>Search By Age :
<select name="age">
<option></option>
<option value="18-20">18-20</option>
<option value="20-25">20-25</option>
</select><input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br />
<div>
Search By Gender:
<select name="salutation">
<option></option>
<option value="0">--- Male ---</option>
<option value="1">--- Female ---</option>
</select> <input type="SUBMIT" name="submit" value="Search >>" />
</div>
<br> <br>
</form>
<?php echo $output; ?>
It seems like you are new to PHP. Here is a solution for you.
First HTML PART. Here use "action" which means that the page will locate the file and process data. For example action="search_process.php". But if you are processing the data from the same page use $_SERVER['PHP_SELF'];
<!-- The HTML PART -->
<form method="POST" action="$_SERVER['PHP_SELF']"> // here it will load the self page
<div>
<p>
Search By name: <input type="text" name="search_name" />
Search By age: <input type="text" name="search_age" />
Search By gender: <input type="TEXT" name="search_gender" />
<input type="submit" name="submit_name" value="Search >>" />
</p>
</div>
Now the PHP part:
<?php
if(isset($_POST['submit_name'])
{
//What happens after you submit? We will now take all the values you submit in variables
$name = (!empty($_POST['search_name']))?mysql_real_escape_string($_POST['search_name']):null; //NOTE: DO NOT JUST USE $name = $_POST['search_name'] as it will give undefined index error (though your data will be processed) and will also be open to SQL injections. To avoid SQL injections user mysql_real_escape_string.
$age = (!empty($_POST['search_age']))?mysql_real_escape_string($_POST['search_age']):null;
$gender = (!empty($_POST['search_gender']))?mysql_real_escape_string($_POST['search_gender']):null;
//Now we will match these values with the data in the database
$abc = "SELECT * FROM table_name WHERE field_name LIKE '".$name."' or field_gender LIKE '".$gender."' or field_age LIKE '".$age."'"; // USE "or" IF YOU WANT TO GET SEARCH RESULT IF ANY OF THE THREE FIELD MATCHES. IF YOU WANT TO GET SEARCH RESULT ONLY WHEN ALL THE FIELD MATCHES THEN REPLACE "or" with "and"
$def = mysql_query($abc) or die(mysql_error())// always use "or die(mysql_error())". This will return any error that your script may encounter
//NOW THAT WE HAVE GOT THE VALUES AND SEARCHED THEM WE WILL NOW SHOW THE RESULT IN A TABLE
?>
<table cellspacing="0" cellpadding="0" border"0">
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
<?php while($row = mysql_fetch_array($def)) { // I HAD MISSED OUT A WHILE LOOP HERE. SO I AM EDITING IT HERE. YOU NEED TO USE A WHILE LOOP TO DISPLAY THE DATA THAT YOU GOT AFTER SEARCHING.
<tr>
<td><?php echo $row[field_name]; ?></td>
<td><?php echo $row[field_age]; ?></td>
<td><?php echo $row[field_gender]; ?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
A perfect solution for your query. All the best.
Well i cant give you the whole code, but here are the few solutions..
Use 3 different forms with 3 different submit buttons.
Use radio buttons on html form, and make a check on PHP side and perform operations depending upon what or which radio is selected.
Use a button instead of submit, radio buttons, hidden fields, and pass data to different php page on form submit (this can be lengthy).
Well you have options.
You can replace your code
if ($resultSet->num_rows > 0) {
with this
if ($resultSet->num_rows > 0 and trim($search) != "") {
so it will not show all results if your input box is empty
hope this will help you
Edit
here is an example you can get idea
$qry = "SELECT * FROM test WHERE 1=1";
if($purpose!="")
$qry .= " AND purpose='$purpose'";
if($location!="")
$qry .= " AND location='$location'";
if($type!="")
$qry .= " AND type='$type'";
and for age
if ($age!='') {
$qry .= " AND age between ".str_replace('-',' and ',$age);
}
When you POST a blank variable and Query with %$search% and 'OR' other criteria, sql matches all records with space in column Name ! So you will have to use some variation of;
If(empty($POST['search']){ ['Query witbout Name parameter']} else{['Query with Name parameter']}
As for converting DOB to match age range. You will have to use
SELECT TIMESTAMPDIFF
answered here
calculate age based on date of birth

MySQL query updating depending on $_POST values

I am having trouble thinking out a good way to update my query depending on user $_POST values. Basically I have user management search button, where site administrator can search for his sites users. In my example:
<div id="website_user_management_search_left">
<div id="website_user_management_search_left_leftside">
<p>Name:</p>
<p>Surname:</p>
<p>Telephone:</p>
<p>Group:</p>
<p>Discount group:</p>
</div>
<div id="website_user_management_search_left_rightside">
<input type="text" name="#" value="#" id="userSearch_name">
<input type="text" name="#" value="#" id="userSearch_surname">
<input type="text" name="#" value="#">
<input type="text" name="#" value="#">
<input type="text" name="#" value="#">
<input type="submit" id="button_adminUserSearch" value="Search">
</div>
Then after pressing "Search" button AJAX sends request to retrieve results, but how can I handle this dynamic query?
For example - if user just presses "Search" query would look like:
mysqli_query($dbconnect,"SELECT * FROM accounts");
For example - if user specifys $_POST["name"] value, query would look like:
mysqli_query($dbconnect,"SELECT * FROM accounts WHERE name='".$_POST["name"]."'");
Problem is - how can I efficiently handle this kind of query? It would be dumb to check which values is "isSet" and then make tons of query cases.
I hope you understood my problem and can help out with it, because it`s kinda hard to explain it.
Maybe you're looking for something like it :
if(empty($_POST['name'])) {
$name = null;
} else $name = $_POST['name'];
Then in your statement, your condition would be :
WHERE (name=:name OR :name is null)
If name isset, it will search for this name, else it will return true and query will not be affected
You could do something like that:
mysqli_query($dbconnect,"SELECT * FROM accounts WHERE name LIKE'%".$_POST["name"]."%'");
But there are two little problems:
You don't have escaped your user input data with mysqli_escape_string() and:
You shouldn't do that. A better way would be to add a where clause only, if name POST data is set:
$where = '';
if ($_POST['name']) {
$where = ' WHERE name = '".$name."'"';
}
mysqli_query($dbconnect,"SELECT * FROM accounts" . $where);

search.php not grabbing results from form

I'm finding it very hard to return database results with php pdo pagination in wordpress. I have a form on another page that sends the search data to search4.php where I want to display matching rows and have previous|next links. I get no results, and If I echo $search, it just says 'search'
Here is the relevant code so far:
//html form on another page
<form method="POST" action="<?www.example.com/search4 ?>">
Search:
<input type="text" name="search"
<input type="submit" name="search" value="search" /></form>
//search4.php relevant code
if(isset($_REQUEST["search"]) && $_REQUEST["search"] != "")
{
$search = htmlspecialchars($_REQUEST["search"]);
$pagination->param = "&search=$search";
echo $search;
$pagination->rowCount("SELECT * FROM stories WHERE stories.category LIKE
'%$search%' OR stories.genre = LIKE '%$search%'");
$pagination->config(3, 8);
$sql = "SELECT * FROM stories WHERE stories.category LIKE '%$search%' OR
stories.genre = LIKE '%$search%' ORDER BY SID ASC LIMIT $pagination-
>start_row, $pagination->max_rows";
$query = $connection->prepare($sql);
$query->execute();
$model = array();
while($rows = $query->fetch())
{
...etc
You <input type=text> and your <input type=submit> has the same name... So button value is overriding your text value... that why is always "search".
change it to:
<input type="text" name="search_text"/>
<input type="submit" name="search_button" value="search" />
Now, on your search4.php you can access your search text using $_REQUEST["search_text"]
PD: You can remove the name attribute on the submit button too.

php searching in more than one column mysql

I am trying to make a code to search for data in more than one column , the code works only if I search in one column. when I tried to search in two columns it says that nothing is found in the database.
<form action="" method="post">
<input type="text" name="param" >
<input type="submit" name="submit" value="search">
</form>
if (isset($_POST['param'])) {
$param= trim ($_POST['param']);
$result = "SELECT * FROM table WHERE student_Name LIKE '%$param%' AND course_name LIKE '%$param%'";
I think you should use OR unless you want to check the 2 columns with the same parameter.
$result = "SELECT * FROM thecars WHERE student_Name LIKE '%$param%' OR course_name LIKE '%$param%'";
Also, this is very open to SQL injection. Sanitize your input before you pass it to the query.
You could do a concat and search via that.
$result = "SELECT * FROM thecars WHERE CONCAT(`student_Name`, `course_name`) AS `search`LIKE '%$param%'";
Your using the same $param variable to search on both columns. If your searching for 2 separate values provide a form that supports inputting 2 values. And then handle such input properly in your query formation.
<form action="" method="post">
<input type="text" name="param1" >
<input type="text" name="param2" >
<input type="submit" name="submit" value="search">
</form>
if (isset($_POST['param1']) || isset($_POST['param2'])) {
$param1 = trim ($_POST['param1']);
$param2 = trim ($_POST['param2']);
$result = "SELECT * FROM thecars WHERE student_Name LIKE '%$param1%' AND course_name LIKE '%$param2%'";
Also change your column aggregation in where clause to OR as suggested by others if your searching for similar outcome.

Searching multiple values

So far i have created a search box, which searches the primary key of my database.
How can i modify my php query to search multiple values in my database.
eg: If i search the name of the car instead of the VIN (primary key) it will show all the results matching the search value.
This
$query = ("SELECT * FROM cars
WHERE VIN='$VIN'");
This is my form :
<form name="search" action="http://www.deakin.edu.au/~sjrem/SIT104_3/cars.php" method="post">
<h2> Search for a car of your choice </h2>
<table border="0">
<tr>
<td><input type="text" name="VIN" /> </td>
</tr>
</table>
<p>
<input type="submit" name="action" value="search" />
</FORM>
Have you tried something like $query = ("SELECT * FROM cars WHERE VIN='$VIN' OR name LIKE '%$VIN%'");?
"LIKE" uses % as wildcard, so it will find all cars that have $VIN in their name.
But anyway make sure to mysql_real_escape_string() your parameter $VIN first, to prevent SQL injections!
Use the following query:
$query = ("SELECT * FROM cars WHERE Name LIKE '%$txtName%'");
NOTE:: Wildcard % is been used at the beginning and end to return all names having your search word anywhere in the field.
something like this might work for you
$query = ("SELECT * FROM cars WHERE VIN='$VIN' OR CARS='$VIN'");

Categories