Php search query with range filter - php

I am trying to do a search query, but not sure how to put everything together. I am having problem with the range filter part.
What i am trying to achieve:
A search form that
1.) If field A,B(not empty) then put in the search query
2.) search through price column with (price lower range, price higher range)
include the results if it matches Field A,B(if it is not empty) and price(if it is in range).
(if search Fields A, B are empty then display all results that exist between range).
Thanks for your time.
The codes that i have now.
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
session_start();
include 'connect.php';
if($_POST)
{
$A = ($_POST['A']);
$B = ($_POST['B']);
$C = ($_POST['C']);
$pricelow = ($_POST['pricelow']);
$pricehigh = ($_POST['pricehigh']);
$sql = array();
if (!empty($A)) {
$sql[] = "A='$A'";
}
if (!empty($B)) {
$sql[] = "B='$B'";
}
if (!empty($C)) {
$sql[] = "C='$C'";
}
if (!empty($price)) {
for($i = pricelow; $i<pricehigh; $i++){
$price = $i;
}
$sql[] = "price='$price'";
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . $sql: '');
$result = mysqli_query($con,$sql);
$output = array();
// fetch your results
while( $row = mysqli_fetch_assoc($result) )
{
// add result row to your output's next index
$output[] = $row;
}
// echo the json encoded object
echo json_encode( $output );
}
?>
Edit:
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . $sql: '') . ("AND" 'price' BETWEEN "$pricelow" AND "$pricehigh");
Edit:
if (!empty($pricelow) || !empty($pricehigh)) {
$sql[] = $pricehigh>= 'price' and 'price'>=$pricelow ;
}
$sql = array();
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');

<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
session_start();
include 'connect.php';
if($_POST)
{
$A = ($_POST['A']);
$B = ($_POST['B']);
$C = ($_POST['C']);
$pricelow = ($_POST['pricelow']);
$pricehigh = ($_POST['pricehigh']);
$query = "SELECT * FROM Listing WHERE ";
$flag = 0;
if (!empty($A)) {
$query .= $flag==0?" A='$A' ":" AND A = '$A'";
$flag = 1;
}
if (!empty($B)) {
$query .= $flag==0?" B = '$B' ":" AND B = '$B'";
$flag = 1;
}
if (!empty($C)) {
$query .= $flag==0?" C='$C' ":" AND C= '$C'";
$flag = 1;
}
if ($flag == 0) {
$query .= " price > $pricelow AND price > $pricehigh"
}
$result = mysqli_query($con,$query);
$output = array();
// fetch your results
while( $row = mysqli_fetch_assoc($result) )
{
// add result row to your output's next index
$output[] = $row;
}
//your rest of the code
>?
I can't test it so, try and report the result!

You are creating an array of conditions and later you try to use that array as a string. This will not work, as the generated query is invalid. Take a look here, implode is a function which implodes an array using a separator. If you use " AND " as separator, then you will get the string you have desired. So, instead of:
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . $sql: '');
do the following:
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');
and your problem should be solved.
EDIT:
I have read your edit and I mean this code in particular:
if (!empty($pricelow) || !empty($pricehigh)) {
$sql[] = $pricehigh>= 'price' and 'price'>=$pricelow ;
}
$sql = array();
$sql = implode(' AND ', $sql);
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');
After you build your array you are initializing it again, thus you lose all information you have processed earlier. Then you implode it twice, which is not needed. Try this way:
if (!empty($pricelow) || !empty($pricehigh)) {
$sql[] = $pricehigh>= 'price' and 'price'>=$pricelow ;
}
$sql = "SELECT * FROM Listing" . (!empty($sql)? " WHERE " . implode(" AND ", $sql): '');

Related

PHP array implode keys and values to function

I'm not too familiar with PHP arrays, I have the following code that generates query to output the results needed.
$allstore = $_POST['store'];
function createSelect($allstore)
{
if (empty($allstore))
return "";
$querySelect = "";
$queryJoin = "";
$baseTable = "";
foreach ($allstore as $store => $value) {
if (!$querySelect) {
$baseTable = $store;
$querySelect = "SELECT " . $store . ".item_no, " . $store . ".actual_price, " . $store . ".selling_price, " . $store . ".qty as " . $store;
} else {
$querySelect .= ", " . $store . ".qty as " . $store;
$queryJoin .= "
INNER JOIN " . $store . " ON " . $baseTable . ".item_no = " . $store . ".item_no";
}
}
$querySelect .= " FROM " . $baseTable;
$query = $querySelect . $queryJoin;
return $query;
}
//Stores to be shown
$allstore = ['s_M9' =>0 , 's_M10' =>1];
$query = (createSelect($allstore));
$result = mysql_query($query);
//rest of code...
As you can see above, at the very top there is $allstore = $_POST['store']; Which collects values based from previous form POST method that has checkbox with the name=store[] .
Now According to the function shown, if I create my own keys and values like this
$allstore = ['s_M9' =>0 , 's_M10' =>1];
the output shows exactly what i'm looking for. But the problem goes on how to let $allstore implode those stores s_M9, s_M10 based on what the user has selected on the previous page ( checkbox )? I mean, the user can select either one of the stores or Both stores . How can I implode the checked results between those brackets without inserting them manually?
Thank You
Edit :
<?php
echo "<form action='somewhere.php' method='POST'>";
$query = "SELECT * from stores_list ORDER BY short Asc";
$result = mysql_query($query);
if(mysql_num_rows($result)>0){
$num = mysql_num_rows($result);
for($i=0;$i<$num;$i++){
$row = mysql_fetch_assoc($result);
echo "<input type=checkbox name=store[] value={$row['short']} style='width:20px; height:20px;'>{$row['short']}";
}
}
else{
//No Stores Available
echo "No Stores Found !";
}
echo "</td><input type='submit' value='Search'/></form>";
$allstore = [];
if (!empty($_POST['store'])) {
foreach ($_POST['store'] as $value) {
$allstore[$value] = 1; // or 0, it doesn't matter because your function adds all the keys
}
}
$query = (createSelect($allstore));
$result = mysql_query($query);
And of course you have to take care of your createSelect function to avoid SQL Injections, please read here

PHP output array into SELECT mysql

Need to find array, and then run a MYSQL SELECT where array values are present (or not present).
$symbol = "abc";
$sql = "SELECT * FROM around";
$results = $conn->query($sql);
foreach($results as $row) {
$stop = preg_replace("/[0-9]/", "", $row['tip']);
if ($stop == $symbol)
{$sword = $row['tip'];
}}
So we need $sword to serve as an array in the event that there are multiple outputs. After we have that array, we need to run a mysql query that shows only those that have $sword array.
$query = "
SELECT * FROM ms WHERE `big` = '$sword'";
$result = mysql_query( $query );
So then we can do something like:
while ( $row = mysql_fetch_assoc( $result ) ) {
echo '"time": "' . $row['time'] . '",'; }
Here's the code, converting $sword to an array and using it in your 2nd query:
$symbol = array("abc", "def", "ghi");
$sword = array();
$sql = "SELECT * FROM around";
$results = $conn->query($sql);
foreach($results as $row) {
$stop = preg_replace("/[0-9]/", "", $row['tip']);
if (in_array($stop, $symbol)) {
$sword[] = $row['tip'];
}
}
if ($sword) {
$in = '';
$sep = '';
foreach ($sword as $s) {
$in .= "$sep '$s'";
$sep = ',';
}
/* $in now contains a string like "'123abc123', '12abc12', '1abc1'" */
$query = "
SELECT * FROM ms WHERE `big` IN ($in)";
$result = mysql_query( $query );
while ( $row = mysql_fetch_assoc( $result ) ) {
echo '"time": "' . $row['time'] . '",';
}
}
Now I'm going to go wash my hands to get all that mysql_query off me... :-)

search query in php

I am creating search query in php by passing variable through GET method. When the variable is null then it's passing the query like,
SELECT * FROM table WHERE column_name = null.
And it's showing error (obvious). I want to create query like. If user don't select anything from search options then it should fetch all the data from that column.
What's the correct logic for that?
Thanks.
Code:
if(isset($_GET['selPetType']) && $_GET['selPetType'] != '')
{
$searchParams['petType'] = $_GET['selPetType'];
$queryStr .= " PetType='" .$_GET['selPetType']. "'";
}
if(isset($_GET['txtPetBreed1']) && !empty($_GET['txtPetBreed1']))
{
$searchParams['breed'] = $_GET['txtPetBreed1'];
$queryStr .= " AND PetBreed1 ='". $_GET['txtPetBreed1'] . "'";
}
$clause1 = "SELECT * FROM pet WHERE $queryStr ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit";
$totalRun1 = $allQuery->run($clause1);
Maybe something like this:
$get['param1'] = 'foo';
$get['param3'] = null;
$get['param2'] = '';
$get['param4'] = 'bar';
$where = null;
foreach ($get as $col => $val) {
if (!empty($val)) {
$where[] = $col . ' = "' . $val . '"';
}
}
$select = 'SELECT * FROM pet ';
if ($where) {
$select .= 'WHERE ' . implode(' AND ', $where);
}
$select .= ' ORDER BY `Avatar` ASC LIMIT $startLimit, $pageLimit';
Edit: I added if to remove empty values and added 2 new values to example so you can see this values will not be in query.
if(isset($_GET['your_variable'])){
$whr = "column_name = $_GET['your_variable']";
}
else{
$whr = "1 = 1";
}
$qry ="SELECT * FROM table WHERE ".$whr;
For example :
<?php
$userSelectedValue = ...;
$whereCondition = $userSelectedValue ? " AND column_name = " . $userSelectedValue : "" ;
$query = "SELECT * FROM table WHERE 1" . $whereCondition;
?>
Then consider it's more safe to use prepared statements.

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

SQL Multiple WHERE Clause Problem

I'm attempting the modify this Modx Snippet so that it will accept multiple values being returned from the db instead of the default one.
tvTags, by default, was only meant to be set to one variable. I modified it a bit so that it's exploded into a list of variables. I'd like to query the database for each of these variables and return the tags associated with each. However, I'm having difficulty as I'm fairly new to SQL and PHP.
I plugged in $region and it works, but I'm not really sure how to add in more WHERE clauses for the $countries variable.
Thanks for your help!
if (!function_exists('getTags')) {
function getTags($cIDs, $tvTags, $days) {
global $modx, $parent;
$docTags = array ();
$baspath= $modx->config["base_path"] . "manager/includes";
include_once $baspath . "/tmplvars.format.inc.php";
include_once $baspath . "/tmplvars.commands.inc.php";
if ($days > 0) {
$pub_date = mktime() - $days*24*60*60;
} else {
$pub_date = 0;
}
list($region, $countries) = explode(",", $tvTags);
$tb1 = $modx->getFullTableName("site_tmplvar_contentvalues");
$tb2 = $modx->getFullTableName("site_tmplvars");
$tb_content = $modx->getFullTableName("site_content");
$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value";
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid ";
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id ";
$query .= " WHERE stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " AND tb_content.pub_date >= '$pub_date' ";
$query .= " AND tb_content.published = 1 ";
$query .= " ORDER BY stc.contentid ASC;";
$rs = $modx->db->query($query);
$tot = $modx->db->getRecordCount($rs);
$resourceArray = array();
for($i=0;$i<$tot;$i++) {
$row = #$modx->fetchRow($rs);
$docTags[$row['contentid']]['tags'] = getTVDisplayFormat($row['name'], $row['value'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
}
if ($tot != count($cIDs)) {
$query = "SELECT name,type,display,display_params,default_text";
$query .= " FROM $tb2";
$query .= " WHERE name='".$region."' LIMIT 1";
$rs = $modx->db->query($query);
$row = #$modx->fetchRow($rs);
$defaultOutput = getTVDisplayFormat($row['name'], $row['default_text'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
foreach ($cIDs as $id) {
if (!isset($docTags[$id]['tags'])) {
$docTags[$id]['tags'] = $defaultOutput;
}
}
}
return $docTags;
}
}
You don't add in more WHERE clauses, you use ANDs and ORs in the already existing where clause. I would say after the line $query .= " WHERE stv.name = '".$region... you put in
foreach ($countries as $country)
{
$query .= "OR stv.name = '{$country}', ";
}
but I don't know how you want the query to work.

Categories