Search - handling empty criteria fields - php

I would need some structure suggestions for fast multiple criteria search.
There are input fields for all table columns to search by.
How to handle empty fields (not filled by user / only search by given information)?
Thanks :)

The best approach is
WHERE
(col1=#col1 or #col1 is null) and
(col2=#col2 or #col2 is null) and
(col3=#col3 or #col3 is null) and
.
.
assuming you pass null if the column is skipped for search

You can build and append the where clause as below
$query ="SELECT fields FROM tableName ";
$where ="";
if(isset($_POST['field1']))
{
$field1= mysql_real_escape_string($_POST['field1']);
if($field1 != '')
{
$where . = "field1Name = $field1 AND ";
}
}
if(isset($_POST['field2']))
{
$field2= mysql_real_escape_string($_POST['field2']);
if($field2 != '')
{
$where . = "field2Name = $field2 AND ";
}
}
$where = rtrim($where, " AND ");
$query . =$where;

Related

PHP filters combining into one SQL query

I'm trying to filter through my database according to filters done by visitors.
$query = "select * from Sheet1 where";
//filter query start
if (!empty($brand)) {
$branddata = implode("','", $brand);
//testing removing query
$query .= " Brand in('$branddata') and";
}
if (!empty($model)) {
$modeldata = implode("','", $model);
//testing removing query
$query .= " Model in('$modeldata') and";
}
/* if(!empty($model) && empty($brand)){
} */
if (!empty($spower) && !empty($epower)) {
$query .= " Power>='$spower' and Power<='$epower' and";
}
if (!empty($sprice) && !empty($eprice)) {
$query .= " Doors>='$sprice' and Doors<='$eprice'";
}
$rs = mysqli_query($conn, $query) or die("Error : " . mysqli_error($conn));
The result I wish to get is a sql query that works and has correct syntax. Such as select * from Sheet1 where Doors>='$sprice' and Doors<='$eprice', if the visitor is filtering by price.
Currently, my code is made so that it simply adds a certain string to the variable. This means that if you don't filter by model, it skips model, because the model variable is empty. The problem comes to if you filter by power, the SQL will become select * from Sheet1 where Power>='$spower' and Power<='$epower' and. Obviously this doesn't work, so I need help in making the code make sure it works for every combination of filters.
Append $query .= " 1 = 1"; at the end. I did some modification in your given code. Have a look.
<?php
$query = "SELECT * FROM `Sheet1` WHERE";
//filter query start
if(!empty($brand)){
$branddata = implode("','",$brand);
$query .= " (Brand in('$branddata')) AND";
}
if(!empty($model)){
$modeldata = implode("','",$model);
$query .= " (Model in('$modeldata')) AND";
}
if(!empty($spower) && !empty($epower)){
$query .= " (Power>='$spower' AND Power<='$epower') AND";
}
if(!empty($sprice) && !empty($eprice)){
$query .= " (Doors>='$sprice' AND Doors<='$eprice') AND"; //Added 'AND'
}
$query .= " 1 = 1"; //Added new line
$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));
?>
Add AND on each query appended in if conditions. Then, at last add $query .= " 1 = 1";. Which will save you from extra AND coming at the end. If none of the conditions satisfy, then your query will be SELECT * FROM Sheet1 WHERE 1 = 1. Simple. And, don't forget to differentiate between conditions in query. Differentiate your conditions like how I did by opening and closing brackets.
I would do it this way
$filters=array();
if(!empty($brand)){
$branddata =implode("','",$brand);
//testing removing query
$filters[]= " Brand in('$branddata')";
}
if(!empty($model)){
$modeldata =implode("','",$model);
//testing removing query
$filters[]= " Model in('$modeldata') and";
}
if(!empty($spower) && !empty($epower)){
$filters[]= " Power>='$spower' and Power<='$epower' and";
}
if(!empty($sprice) && !empty($eprice)){
$filters[]= " Doors>='$sprice' and Doors<='$eprice'";
}
$query = "select * from Sheet1 where";
foreach ($filters as $filter) {
$query.=' AND '.$filter;
}
$rs = mysqli_query($conn,$query) or die("Error : ".mysqli_error($conn));

php mysql order by relevance

$fields = array('surname', 'firstname', 'maiden', 'birth', 'death', 'obittext'); $conditions = array();
foreach($fields as $field){
if(isset($_POST[$field]) && $_POST[$field] != '') {
$conditions[] = "`$field` LIKE '%" . $_POST[$field] . "%'";
}
}
$sql = "SELECT * FROM obits ";
if(count($conditions) > 0) {
$sql .= "WHERE " . implode (' AND ', $conditions);
}
$result = mysqli_query($con, $sql);
So far this allows me to search either one or more than one field like a surname and/or a date of birth. What I would like to do is also sort this by relevance as it currently sorts by the primary ID (ex: I want smith to come before klingensmith if I search smith).
I am really new at this, getting this far required much gnashing of teeth so please explain like I'm 5. I already tried:
$result = mysqli_query($con, $sql, ' ORDER BY relevance DESC ');
which just broke it. I suspect I need to add another condition but I don't know what or where. Very much thanks, and much respect to all you people who understand this stuff.

Multiple textbox for search results

Hello I have a page with multiple textboxes, each textbox should search with its own query. Im using the following php code for this:
php
if ($val != null){
$where = " WHERE boekingsnummer LIKE '".$val."%'";
}
How can I get it to work with the other textboxes ?
Any help is much appreciated.
You could do something like this:
$where = " WHERE 1 = 1 ";
$where .= "AND boekingsnummer LIKE '".$val."%' ";
$where .= "AND ?? LIKE '".$val2."%' ";
Use like this
$sql_add= '';
if ($val1 != '')
{
$sql_add = " AND boekingsnummer LIKE '".$val1."%'";
}
if ($val2 != '')
{
$sql_add .= " AND field2 = '".$val2."%'";
}
and so on....
$sql = "SELECT * FROM TABLE_NAME WHERE 1=1 $sql_add";
may this will help you

Setting up SQL queries with multiple parameters

I need to set up a SQL query with multiple parameters that are being pulled from the URL. So far I can only get it to work with the there is only one item in the URL.
My default query to pull in all the content
$sql = "SELECT ";
$sql .= "* ";
$sql .= "FROM ";
$sql .= "cms_site_content ";
$sql .= "WHERE ";
$sql .= "1";
I then check if anything was passed through the URL and retrieve it.
if (isset($_GET["d"])) {
$d=$_GET["d"];
Inside the if statement, I break the values passed as "d" into separate items
$newD = explode(',',$d);
$countD = count($newD);
foreach($newD as $discipline) {
if ($countD == 1) {
$sql .= " AND";
$sql .= " discipline='".$discipline."'";
}
My problem is getting the SQL to work if there is more than one discipline value. It should read something like this:
SELECT * FROM cms_site_content WHERE 1 AND discipline="value"
however if there's more than one discipline value, it should read:
SELECT * FROM cms_site_content WHERE 1 AND discipline="value OR discipline="value2" OR discipline="value3"
Is there a more efficient way to write this? I can't figure out how to insert the OR into the foreach statement.
Save all discipline values in an array;
$discipline_arr = array();
foreach($newD as $discipline) {
$discipline_arr[] = $discipline;
// by the way, don't forget to escape for sql injection
// mysql_escape_string is the depracated one, u can use that if u have no
// other choice
}
Then in your sql, add them as discipline in ('value1','value2', 'etc ...') condition (that is for strings, for numeric types it would be like discipline in (1,2,3,4, etc)
$sql = " SELECT * FROM cms_site_content WHERE 1 " .
(empty($discipline_arr) ? "" : "and
discipline in ('". implode("','" , $discipline_arr). "') ") ;
Link to escaping
http://tr1.php.net/manual/en/function.mysql-escape-string.php
Assuming the rest of your query is in tact. Simply store all of your discipline values in an array as follows, then feed the $discipline_string to your $sql query:
$discipline_ary = array('option1', 'option2', 'option3');
$discipline_string = "";
for($i=0; $i < count($discipline_ary); $i++){
$discipline_string .= " discipline = '" . $discipline[$i] . "' ";
if($i+1 == count($discipline_ary)){
break;
}else{
$discipline_string .= " OR "
}
}

sql string escaping question

Is it possible to insert the same value more than once into an escaped string? ie
$wpdb->prepare("SELECT * FROM table WHERE (column1 = %s || column2 = %s || column3 = %s) AND this = $s", $search_terms,$that");
If not, does anyone have a good alternative for a condition builder. The SQL is run more than once, on a selection of tables. Some tables have more columns to be searched than others, so I created a condition builder. But now I'm trying to escape the values to prevent SQL injects.
$conditions = "";
$query_seperator = " || ";
$i = 0;
foreach($table['fields'] as $field){
if ($i < ($field_count-1)){
$conditions = $conditions . $field . " LIKE %s" . $query_seperator;
} else {
$conditions = $conditions . $field . " LIKE %s";
}
$i++;
}
$wpdb->prepare("SELECT * FROM table WHERE ($conditions) AND this = $s", $search_terms,$that");
Your query seems to be equivalent to
$wpdb->prepare("SELECT * FROM table WHERE %s IN (column1,column2,column3) AND this = $s", $search_terms,$that");

Categories