Query to find out advance search option - php

I have tried to find out searching from 3 fields. If I will fill only 1 field then data should search, if i will fill in 2 columns then data should search.
Help me out where i am wrong as data is searching from any scenario.
Below is my code which i have used but it not working :-
$query = "";
$keyword = $_REQUEST['sports'];
$country = $_REQUEST['city'];
$category = $_REQUEST['code'];
if(isset($keyword)){//if keyword set goes here
$query = "SELECT * FROM event WHERE sports LIKE '%$keyword%' OR postelcode LIKE '%$keyword%' OR city LIKE '%$keyword%'";
if(isset($category)){
$query = "AND postelcode LIKE '$category'";
}
if(isset($country)){
$query = "AND city LIKE '$country'";
}
}else if (isset($category)){ //if keyword not set but category set then goes here
$query = "SELECT * FROM event WHERE postelcode LIKE '$category'";
if(isset($country)){
$query = "AND city LIKE '$country'";
}
}else if(isset($country)){//if only country set goes here
$query = "SELECT * FROM event WHERE city LIKE '$country'";
}
$result1 = mysqli_query($conn, $query);
if (mysqli_num_rows($result1) > 0)
{
// output data of each row
while($row = mysqli_fetch_assoc($result1))
{
?> <ul>
<li>Contact Email :- <?php echo $email; ?></li>
<li>Sports :- <?php echo $row["sports"]; ?></li>
</ul>
<?php
}
}
?>

$query = "AND postelcode LIKE '$category'"; is logic which replaces your query. You need to append to it with .= if you're going to add conditions to the WHERE clause. Each instance of trying to add AND logic to your query needs to append to your select query, not replace it.

You're replacing $query variable value with each condition you are adding.
Use .= operator to append the new where clause to the previous query string.
Plus I have made some other changes which will make your code immune to errors by setting up isset to Request variable and replacing isset of where clause variables with !empty because you have already defined all the variables in the beginning of the code. So isset() will always be true.
$query = "";
$keyword = isset($_REQUEST['sports']) ? $_REQUEST['sports'] : ''; //Checking if parameter is passed
$country = isset($_REQUEST['city']) ? $_REQUEST['city'] : '' ; //Checking if parameter is passed
$category = isset($_REQUEST['code']) ? $_REQUEST['code'] : ''; //Checking if parameter is passed
if(!empty($keyword)){//if keyword set goes here
$query = "SELECT * FROM event WHERE sports LIKE '%$keyword%' OR postelcode LIKE '%$keyword%' OR city LIKE '%$keyword%'";
if(!empty($category)){
$query .= " AND postelcode LIKE '$category'"; // Added space before AND
}
if(!empty($country)){
$query .= " AND city LIKE '$country'"; // Added space before AND
}
}else if (!empty($category)){ //if keyword not set but category set then goes here
$query = "SELECT * FROM event WHERE postelcode LIKE '$category'";
if(!empty($country)){
$query .= " AND city LIKE '$country'"; // Added space before AND
}
}
if(isset($country)){//UPDATED THIS CONDITION: if only country set goes here
$query = "SELECT * FROM event WHERE city LIKE '$country'";
}
$result1 = mysqli_query($conn, $query);
if (mysqli_num_rows($result1) > 0)
{
// output data of each row
while($row = mysqli_fetch_assoc($result1))
{
?> <ul>
<li>Contact Email :- <?php echo $email; ?></li>
<li>Sports :- <?php echo $row["sports"]; ?></li>
</ul>
<?php
}
}

Removed the unneeded if blocks and improper string concatinations (subsequent $query =".."; $query =".."; $query =".."; ) that just overwrite previous value of $query.
Use .= operator instead to combine strings - like - $query = "text1 "; $query .= "text2 "; $query .= "text3"; - that results to - $query = "text1 text2 text3";
Also did proper initiation of variables ($keyword, $country and $category) to prevent notice errors. Also mysqli_real_escape_string() on the variables to prevent sql injection attacks.
The below code returns records that matches any of the search fields using mysql OR condition.
Updated Code:
$query = "";
$keyword = mysqli_real_escape_string($conn, ((isset($_REQUEST['sports']) AND $_REQUEST['sports'] != "" )? "%{$_REQUEST['sports']}%" : ''));
$country = mysqli_real_escape_string($conn, ((isset($_REQUEST['city']) AND $_REQUEST['city'] != "" )? "%{$_REQUEST['city']}%" : ''));
$category = mysqli_real_escape_string($conn, ((isset($_REQUEST['code']) AND $_REQUEST['code'] != "" ) ? "%{$_REQUEST['code']}%" : ''));
if($keyword!="" OR $country!="" OR $category!=""){
$query = "SELECT * FROM event WHERE sports LIKE '$keyword' OR postelcode LIKE '$category' OR city LIKE '$country'";
$result1 = mysqli_query($conn, $query);
if (mysqli_num_rows($result1) > 0) {
while($row = mysqli_fetch_assoc($result1)) {
?>
<ul>
<li>Contact Email :- <?php echo $email; ?></li>
<li>Sports :- <?php echo $row["sports"]; ?></li>
</ul>
<?php
}
}
}
The below code searches in all columns and returns records that match all search fields using mysql AND condition.
Alternative Code:
$query = "";
$keyword = mysqli_real_escape_string($conn, ((isset($_REQUEST['sports']) AND $_REQUEST['sports'] != "" )? "%{$_REQUEST['sports']}%" : ''));
$country = mysqli_real_escape_string($conn, ((isset($_REQUEST['city']) AND $_REQUEST['city'] != "" )? "%{$_REQUEST['city']}%" : ''));
$category = mysqli_real_escape_string($conn, ((isset($_REQUEST['code']) AND $_REQUEST['code'] != "" ) ? "%{$_REQUEST['code']}%" : ''));
if($keyword!="" OR $country!="" OR $category!=""){
$query = "SELECT * FROM event WHERE ";
if($keyword!="") {
$query .= "sports LIKE '$keyword'";
}
if($category!="") {
if($keyword!=""){
$query .= " AND "
}
$query .= "postelcode LIKE '$category'";
}
if($county!="") {
if($keyword!="" OR $category!="") {
$query .= " AND "
}
$query .= " city LIKE '$country'";
}
$result1 = mysqli_query($conn, $query);
if (mysqli_num_rows($result1) > 0) {
while($row = mysqli_fetch_assoc($result1)) {
?>
<ul>
<li>Contact Email :- <?php echo $email; ?></li>
<li>Sports :- <?php echo $row["sports"]; ?></li>
</ul>
<?php
}
}
}

Related

Querying mySQL database with dropdown values

I've got below snippet where $filter_xx values are extracted from a dropdown basis user choice.
I'm trying to query the mySQL database with what the user chose to query the database with via dropdown selection.
You will see that there are 4 $filter_xx variables and how many of them are set in a given instance is completely random.
The issue is when I use && in the query it checks if all four parameters are true and then throws and output. (Well I know && is suppose to work that way!). I tried replacing all && operators with || and had no luck.
How do I search the database with only options selected by the user?
if(isset($filter_brand) || isset($filter_year) || isset($filter_month) || isset($filter_status))
{
$query = "SELECT * FROM targets WHERE brand='$filter_brand' && startyear='$filter_year' && startmonth='$filter_month' && status='$filter_status' ORDER BY createdon DESC";
} else {
$query = "SELECT * FROM targets ORDER BY createdon DESC";
}
When you have several values that must work in a similar manner, use an array together with loop. I am supposing, you are using mysqli, change quoting for PDO if needed.
$mysqli = new mysqli("localhost", "user", "pass", "test");
//...
//SQL attr name => name of POST parameter
$filter = array('brand' => 'brand', 'startyear' => 'year',
'startmonth' => 'month', 'status' => 'status');
//here we'll store SQL conditions
$sql_filter = array();
foreach($filter as $key => $value)
{
if (isset($_POST[$value]))
{
//use your library function to quote the variable before using it in SQL
$sql_filter[] = $key . '="'. $mysqli->escape_string($_POST[$value]) . '"';
}
}
$query = "SELECT * FROM targets ";
if(isset($sql_filter[0]))
{
$query .= 'WHERE ' . implode(' AND ', $sql_filter) . ' ';
}
$query .= 'ORDER BY createdon DESC';
Try By This
$join = "";
//TAKE ONE BLANK VARIBLE THAT JOIN IF VALUE IS SET
if(isset($filter_brand)){
//IF VALUE ISSET THAN IT ADDED TO QUERY
$join .= " AND brand='$filter_brand'";
}
if(isset($filter_year){
$join .= " AND startyear='$filter_year'";
}
$query = "SELECT * FROM targets WHERE id != '' $join ORDER BY createdon DESC";
You can do something like this:
$query = 'SELECT * FROM targets';
$flag = 0;
if(isset($filter_brand) )
{
$query = "SELECT * FROM targets WHERE brand='$filter_brand'";
$flag = 1;
}
if(isset($filter_year)) {
if($flag==1)
$query .= " &&";
$query .= " startyear='$filter_year'";
$flag = 1;
}
if(isset($filter_month)) {
if($flag==1)
$query .= " &&";
$query = " startmonth='$filter_month'";
$flag = 1;
}
if(isset($filter_status)){
if($flag==1)
$query .= " &&";
$query = " status='$filter_status'";
$flag = 1;
}
if($flag == 1){
$query .= " ORDER BY createdon DESC";
} else {
$query = "SELECT * FROM targets ORDER BY createdon DESC";
}
Try this:
$query = "SELECT * FROM targets WHERE 1 ";
$query = isset($filter_brand) ? $query . " AND brand = '".$filter_brand."'" : $query;
$query = isset($filter_year) ? $query . " AND startyear = '".$filter_year."'" : $query;
$query = isset($filter_month) ? $query . " AND startmonth = '".$filter_month."'" : $query;
$query = isset($filter_status) ? $query . " AND status = '".$filter_status."'" : $query;
$query .= " ORDER BY createdon DESC";

php instant search, display data return with radio button

I have an instant search built using php. Basically what I would like to do is have each item that is returned by the search have a radio button attached to it. When the button is clicked by the user I would like to have the name of that item stored in an array. I cannot seem to find much useful documentation for doing something like this. Here is my current search.php code.
<?php
mysql_select_db("wesco");
$searchArray = explode(" ", $_POST['searchterm']);
$query = "";
foreach($searchArray as $val) {
set_time_limit(0);
ignore_user_abort(1);
$search = mysql_real_escape_string(trim($val));
if (!empty($query)) {
$query = $query . " AND";
}
$query = $query . "`keywords` LIKE '%$search%'";
}
if (!empty($query)) {
$find_parts = mysql_query("SELECT * FROM `parts` WHERE $query");
}
if(empty($query)){
$searchArray = explode(" ", $_POST['searchterm']);
$query = "";
}
while($row = mysql_fetch_assoc($find_parts))
{
$name = $row['name'];
echo "<center>$name</center><br />";
}
?>

php Search engine the keywords are not working

When i would search for the keywords that i have specified in my database it will return everything from my database not just the corresponding links that have the keywords attached to the link. here is my code
<?php
$q = $_GET['q'];
$terms = explode(" ", $q);
$query = "SELECT * FROM search ";
foreach ($terms as $each){
$i=0;
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
//connect
mysql_connect("localhost", "root", "");
mysql_select_db("search");
$query = mysql_query("SELECT * FROM search");
$numrows = mysql_num_rows($query);
if ($numrows > 0){
while($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h3><a href='$link'>$title</a></h3><h4>$link</h4>$description<br /><br />";
}
}
else
echo "<b>No Results Found</b><br><br>Suggestions:<br>
Make sure all words are spelled correctly.<br>
Try different keywords.<br>
Try more general keywords.";
//disconnect
mysql_close();
?>
<?php
$q = $_GET['q'];
$terms = explode(" ", $q);
//connect
mysql_connect("localhost", "root", "");
mysql_select_db("search");
$query = "SELECT * FROM search ";
$i=1;
foreach ($terms as $each){
if ($i == 1) {
$query .= "WHERE ";
$query .= "keywords LIKE '" . mysql_real_escape_string("%" . $each . "%") . "' ";
} else {
$query .= "OR keywords LIKE '" . mysql_real_escape_string("%" . $each . "%") . "' ";
}
$i++;
}
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0){
while($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h3><a href='$link'>$title</a></h3><h4>$link</h4>$description<br /><br />";
}
} else {
echo "<b>No Results Found</b><br><br>Suggestions:<br>
Make sure all words are spelled correctly.<br>
Try different keywords.<br>
Try more general keywords.";
}
//disconnect
mysql_close();
?>
Fixes:
1) Removed second $query that was being defined. It selected all rows.
2) Moved initial $i declaration. It was being set back to 0 each loop.
3) Added WHERE
4) Moved $i++ after the if statement and set initial $i to 1.
5) Added mysql_real_escape_string so that data is escaped properly.
Recommendations:
I highly recommend taking a look at MySQLi (http://us2.php.net/mysqli) or PDO (http://us3.php.net/pdo)
Please let me know if this works or if you need further assistance.
A first sight, i see a couple of errors.
$i=0;
$i++;
if ($i == 1)
$i Will ALWAYS be one are.
you might want to move $i = 0; BEFORE the foreach
$query = mysql_query("SELECT * FROM search");
You build a query, but in the end you're not using it. you probably want to do : $query = mysql_query($query); instead. ( and also for code clarity using a different variable name for the output ? ) .
mysql_query is deprecated. Useless you're in a hurry, check PDO
First, you're missing the WHERE keyword before the conditions. So it should be:
foreach ($terms as $i => $each){
$each = mysql_real_escape_string($each); // Prevent SQL injection
if ($i == 0)
$query .= "WHERE keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
You don't need to increment your own counter variable, you can use the array indexes from $terms.
Second, after all that work to create $query, you're not using it. You wrote:
$query = mysql_query("SELECT * FROM search");
That should be:
$query = mysql_query($query);
BTW, it's generally a bad idea to reuse variables like that, it gets confusing when you use the same variable for different things. I suggest you call the second $query something like $results.
Change this line
$query .= "keywords LIKE '%$each%' ";
By
$query .= " Where keywords LIKE '%$each%' ";
And also cnhange this line
$query = mysql_query("SELECT * FROM search");
By
$query = mysql_query($query);

creating a sql query dynamically

I want to create sql queries dynamically depending upon the data I receive from the user.
Code:
$test = $_POST['clientData']; //It can be an array of values
count($test); //This can be 2 or 3 or any number depending upon the user input at the client
$query = "select * from testTable where testData = ".$test[0]." and testData = ".$test[1]." and . . .[This would vary depending upon the user input]"
Is it possible to achieve the above scenario. I am relatively new in this area.Your guidance would be helpful.
Use:
<?php
$test=$_POST['clientData'];//It can be an array of values
$query = "select *from testtable where 1 ";
foreach($test as $value) {
$query .= " AND testData='" . $value . "'";
}
echo $query;
?>
Use prepared statements:
$query = $dbh->prepare("SELECT * FROM testtable WHERE testData=:test0 and testData=:test1");
$query ->bindParam(':test0', $test0);
$query ->bindParam(':test1', $test0);
$test0 = $test[0];
$test1 = $test[1];
$query->execute();
Rishi that's a very long chapter.
If you want to search into a single field then you can try to do:
<?php
$test = $_POST[ 'clientData' ];
if( is_array( $test ) ){
$select = implode( ",", $test );
} else {
$select = $test;
}
$query=select *from testtable where testData IN ( $select );
?>
This is valid only for searches into a specific field.
If you want to create searches on multiple fields then you need to do a lot of more work, having an associative mapping which can create a relation variable name -> field_to_search
$data = $_POST['data'];
$query = "SELECT";
if ( is_set($data['columns']) )
$query .= " ".implode(',',$data['columns']);
else
$query .= "*";
if ( is_set($data['table']) )
$query .= " ".$data['table'];
and ...
This is very much pseudo code as I don't really know PHP, but could you not do something like this
$query = "select * from testable";
$count = count($test);
if($count > 0)
{
$query .= " where ";
for ($x=0; $x<=$count; $x++)
{
if($x > 0)
{
$query .= " and ";
}
$query .= " testData='" . $test[x] . "'";
}
}
$test=$_POST['clientData'];
$query="select * from testtable where testData='".$test[0]."' and testData='".$test[1]."' and . . .[This would vary depending upon the user input]";
$result = mysql_query($query);
$test=$_POST['clientData'];//It can be an array of values
$dValuesCount = count($test);//This can be 2 or 3 or any number depending upon the user input at the client
$query="select *from testtable ";
if ($dValuesCount > 0 ){
$query .= " WHERE ";
for ($dCounter = 0; $dCounter <= $dValuesCount ; $dCounter++){
$query .= "testData=" . $test[$dCounter];
if ($dCounter != ($dValuesCount - 1)){
$query .= " AND ";
}
}
}
$q="select *from table where ";
$a=count($test)-1;
$b=0;
while($element = current($test)) {
$key=key($array);
if($b!=$a){
$q.=$key."=".$test[$key]." and ";
}
else {
$q.=$key."=".$test[$key];
}
next($array);
$b=$b+1;
}
for this your array must contain columnname as key
for example
$test['name'],$test['lastname']
then it will return
$q="select * from table where name=testnamevalue and lastname=testlastnamevalue";
hope it works

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