Search box with various filters - php

I have a table name voice with tele_no, date_time and appointment as records. I am trying filter with various combination. If i use OR then it include all fields, If i use AND then all fields must be entered. How to use combination, mean if i type single field or combination of multiple fields. It should return query
$result =mysqli_query($hello,"
SELECT voice.*
, record.*
FROM voice (voice.tele_no = '$tele' AND voice.tele_no<>'')
OR (voice.date_time between '$date_fm' and '$date_to' AND voice.date_time<>'')
OR (voice.appointment= '$tele' AND voice.appointment<>'')

I would use a flexible prepared statement here, something like:
SELECT *
FROM voice
WHERE
(tele_no = ? OR tele_no IS NULL) AND
(date_time BETWEEN ? AND ? OR date_time IS NULL) AND
(appointment = ? OR appointment IS NULL);
Should any of the three columns appearing in the WHERE clause be NULL, then that particular condition would effectively no-op and logically drop out of the query. Note that to implement this from PHP, you would need to use one of several PHP's prepared statement libraries.

Related

How to use wildcard in PHP query

I have a table filter feature in PHP club membership webpage. I made it so the user can filter the table and choose which members to display in a table. For example, he can choose the country or state where the member is from then hit display. I am using a prepared statement.
The problem is, I need to use wildcards to make the coding easier. How do I use a wildcard in PHP MySQL query? I will use wildcards for example if the user does NOT want specific country but instead he wants to display all members from all countries.
I know not specifying the WHERE country= will automatically select any countries but I already constructed it so each controls like the SELECT control for country already has a value like "CA" or "NY" and "*" if the user leaves that control under "All Countries". This value when submitted is then added to the query like:
$SelectedCountry = $_POST["country"];
sql .= " WHERE country=" . $SelectedCountry;
But the problem is using WHERE country=* doesn't seem to work. No errors, just doesn't work. Is "*" the wildcard in PHP MySQL?
The * is not a wildcard in SQL when comparing with the = operator. You can use the like operator and pass a % to allow for anything.
When doing this the % should be the only thing going to the bind. $Bind_country = "'%'"; is incorrect because the driver is already going to quote the value and escape the quotes. So your query would come out as:
WHERE country ='\'%\''
The = also needs to be a like. So you want
$bind_country = '%';
and then the query should be:
$sql = 'select * from table where country like ?';
If this were my application I would build the where part dynamically.
Using * in WHERE clause is not right. You can only give legit value. For example:
// looking for an exact value
SELECT * FROM table WHERE column = 'value'
// you can also do this when looking for an exact value
// it works even if your $_POST[] has no value
SELECT * FROM table WHERE column = 'value' OR '$_POST["country"]' = ''
// looking for a specific or not exact value
// you can place % anywhere in value's place
// % denotes the unknown characters of the value
// it works also even if your $_POST[] has no value
// results will not be the same when you're using AND or OR clause
SELECT * FROM table WHERE column LIKE '%val%'
I think below link can solve your problem.
Just have a look and choose what you need.
Thanks.
http://www.w3schools.com/sql/sql_wildcards.asp

what is the use of putting FALSE in select query when using DATE FORMAT in codeigniter

I want to know reason behind the below code
$this->db->select("DATE_FORMAT(`current_date`, '%M-%d-%Y' ) as date_human", FALSE);
When i'm using the above code, it is returning a result July-09-2015, Now i want to know what is the use of FALSE here.Because I'm getting the same result when not adding FALSE.
I have referred the [LINK](Date format with codeigniter igniter). In this, the expert says that it will stop CI from trying to auto-protect these names.
Edit:
When I use $this->db->last_query, the query i'm getting is:
SELECT *, DATE_FORMAT(current_date, '%M-%d-%Y' ) as date_human FROM `user_data` WHERE id = '57'
when using both FALSE and without FALSE.
I want to know the difference and also the use of FALSE.
Guide me to proceed.
When you use $this->db->select() CodeIgniter auto protect your column names.
If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.
This is useful if you need a compound select statement.
Example
$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE);
$query = $this->db->get('mytable');
Read CodeIgniter active_record.html#select
$this->db->select() accepts an optional second parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names. This is useful if you need a compound select statement where automatic escaping of fields may break them.
e.g.
$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4) AS amount_paid', FALSE);
$query = $this->db->get('mytable');
Refer :
http://www.codeigniter.com/user_guide/database/query_builder.html

What character can i use in mysql query to represent all results?

Im trying to create a php script that queries a database based on filter input from users
So essentially i want
select * from table where parent_id = '$filter_value'
However i want to apply a default value to $filter_value which will take effect if the user doesnt specify any filters, and will pull up all possible results.
I tried using * but it didnt work...
Two ways:
Compare the value to NULL
SELECT *
FROM table
WHERE ($filter_value IS NULL OR parent_id = '$filter_value')
Dynamically create the SQL based on whether $filter_value contains a value. If it does not, your query should simply be:
SELECT *
FROM table
Check if the filter variable is null, or just wrap your query in an if statement:
SELECT * FROM baz WHERE foo = :bar OR :bar IS NULL
It's not exactly what you asked, but it is very close and I think a better way. You can do something like this:
if ( empty( $filter_value ) === false ) {
select * from table where parent_id = '$filter_value'
} else {
select * from table
}
That is just an example, not good php syntax.
But the idea is that if you want to have different behaviours depending on something, then you should program it that way, for instance, with an if, that way, you know what happens in each case and control the situation, not depending on what mysql does with the empty value passed.
Ok, i tried just inserting a blank space as the default var value, as in
$filter_value = ''
Solved the problem :$

PHP SQL Search Form Syntax

I have a php form that searches a SQL database. There are say eight form fields each of which are optional. If everything is left blank, the query will return the entire database. If one field is filled out it will filter by one field, two it will filter by two, etc. I haven't had any issues until I wanted the ability to search for null entries. So for example I want to search where the customers has a last name but DOES NOT have a primary phone number. I've been working for a couple hours and can't think of a simple way to implement something like this. I envision it as you type a keyword into the search field to search where the item is null on top of everything else. So if I put "Smith" into last name and "NULL" into phone number it would work with my above example. Below is my current code.
$query = "SELECT *
FROM customer_search_view
WHERE COALESCE(customer_search_view.first_name,'') LIKE $firstName AND
COALESCE(customer_search_view.last_name,'') LIKE $lastName AND
COALESCE(customer_search_view.customer_id,'') LIKE $customerId AND
COALESCE(customer_search_view.primary_phone,'') LIKE $primaryPhone AND
COALESCE(customer_search_view.email,'') LIKE $email AND
COALESCE(customer_search_view.store,'') LIKE $store AND
COALESCE(customer_search_view.sales_associate,'') LIKE $salesAssociate AND
COALESCE(customer_search_view.bdr_associate,'') LIKE $bdrAssociate AND
COALESCE(customer_search_view.status,'') LIKE $status AND
COALESCE(customer_search_view.lead_category,'') LIKE $leadCategory
ORDER BY created_on DESC LIMIT 0,100";
If there is anyway to search where something is LIKE NULL it would be a quick fix as well.
the only way to find NULL is to use COALESCE(customer_search_view.primary_phone,'') IS NULL so you would need to extend your variables to be like
COALESCE(customer_search_view.primary_phone,'') $primaryPhoneOperator $primaryPhone
If you can't change your front end you could loop through values before your query such as
if(empty($primaryPhone)) { $primaryPhoneOperator = "IS NULL"; } else { $primaryPhoneOperator = "LIKE"; }

How to filter by multiple fields in MySQL/PHP

I'm writing a filter/sorting feature for an application right now that will have text fields above each column. As the user types in each field, requests will be sent to the back-end for sorting. Since there are going to be around 6 text fields, I was wondering if there's a better way to sort instead of using if statements to check for each variable, and writing specific queries if say all fields were entered, just one, or just two fields, etc.
Seems like there would be a lot of if statements. Is there a more intuitive way of accomplishing this?
Thanks!
Any initial data manipulation, such as sorting, is usually done by the database engine.
Put an ORDER BY clause in there, unless you have a specific reason the sorting needs done in the application itself.
Edit: You now say that you want to filter the data instead. I would still do this at the database level. There is no sense in sending a huge dataset to PHP, just for PHP to have to wade through it and filter out data there. In most cases, doing this within MySQL will be far more efficient than what you can build in PHP.
Since there are going to be around 6 text fields, I was wondering if there's a better way to sort instead of using if statements to check for each variable
Definitely NO.
First, nothing wrong in using several if's in order.
Trust me - I myself being a huge fan of reducing repetitions of code, but consider these manually written blocks being the best solution.
Next, although there can be a way to wrap these condition ns some loop, most of time different conditions require different treatment.
however, in your next statements you are wrong:
and writing specific queries
you need only one query
Seems like there would be a lot of if statements.
why? no more than number of fields you have.
here goes a complete example of custom search query building code:
$w = array();
$where = '';
if (!empty($_GET['rooms'])) $w[]="rooms='".mesc($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mesc($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mesc($_GET['max_price'])."'";
if (count($w)) $where="WHERE ".implode(' AND ',$w);
$query="select * from table $where";
the only fields filled by the user going to the query.
the ordering is going to be pretty the same way.
mesc is an abbreviation for the mysql_real_escape_string or any other applicable database-specific string escaping function
select * from Users
order by Creadted desc, Name asc, LastName desc, Status asc
And your records will be sorted by order from query.
First by Created desc, then by Name asc and so on.
But from your question I can see that you are searching for filtering results.
So to filter by multiple fileds just append your where, or if you are using any ORM you can do it through object methods.
But if its simple you can do it this way
$query = "";
foreach($_POST['grid_fields'] as $key => $value)
{
if(strlen($query) > 0)
$query .= ' and '
$query .= sprintf(" %s LIKE '%s' ", mysql_real_escape_string($key), '%' .mysql_real_escape_string($value) .'%');
}
if(strlen($query) > 0)
$original_query .= ' where ' . $query;
this could help you to achieve your result.
No. You cannot avoid the testing operations when sorting the set, as you have to compare the elements in the set in same way. The vehicle for this is an if statement.
Could you take a look at this?
WHERE (ifnull(#filter1, 1) = 1 or columnFilter1 = #filter1)
and (ifnull(#filter2, 1) = 1 or columnFilter2 = #filter2)
and (ifnull(#filter3, 1) = 1 or columnFilter3 = #filter3)
and (ifnull(#filter4, 1) = 1 or columnFilter4 = #filter4)
and (ifnull(#filter5, 1) = 1 or columnFilter5 = #filter5)
and (ifnull(#filter6, 1) = 1 or columnFilter6 = #filter6)
Please let me know if I'm misunderstanding your question.. It's not like an IF statement batch, and is pretty lengthy, but what do you think?

Categories