<?php
if(isset($_POST['submit'])) {
$fields = array('field1', 'field2', 'field3');
$conditions = array();
foreach($fields as $field){
if(isset($_POST[$field]) && $_POST[$field] != '') {
$conditions[] = "`".$field."` like '%" . mysql_real_escape_string($_POST[$field]) . "%'";
}
}
$query = "SELECT * FROM customer ";
if(count($conditions) > 0) {
$query .= "WHERE " . implode (' AND ', $conditions);
}
$result = mysql_query($query);
$say = mysql_num_rows($result);
if ($say == 0) {
echo "<tr>no result.</tr>";
} else {
echo '...';
while($row = mysql_fetch_array($result))
{
...
}}
} ?>
Why doesn't this code checking empty fields? It returns results that has empty field even form submits empty.
The only improvement I think of is trim():
if(isset($_POST[$field]) && trim($_POST[$field]) != '') {
however, I am sure it is not the issue.
Have you ever thought of printing the resulting query out?
Look, you're writing a program to create some string (SQL query). But for some reason never interested in this program's direct result, judging it by some indirect results. May be it's data/query logic makes such results, but the query itself is okay?
if the query is still wrong - continue debugging.
Echo everything involved - print variables, condition results, intermediate results in the loop - and look for inconsistencies
$query = "SELECT * FROM customer ";
if(count($conditions) > 0) {
$query .= "WHERE " . implode (' AND ', $conditions);
}
When form is submitted empty ($conditions=0) it returns all table (select * from customer).
Added an else condition and fixed. Thanks for print query advices.
For checking something is empty or not. You can use empty() method.
Check this:
empty()
isset() only check whether that object/variable is set or not. For more details check this
isset()
Related
I've been trying to debug this script for a month. The rest of the program is already built and this one thing just will not work. The issue is the $query variable, it returns null unless I hard code - which isn't possible with a search form. I've tried adding '\n', I've tried just putting in the returns, I've changed the " to ' for the beginning. I've tested the rest of the code outside of this block and it all works. I've run tests on this block as you can see from commented out echo statements below. Those all test fine. The $query string built by the function returns the correct data when hard coded or in the database browser. I'm stuck! Help please.
[code snippet]
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('lastname', 'firstname', 'dob', 'city', 'telephone', 'email', 'user_id');
$conditions = array();
// loop through the defined fields
foreach($fields as $field){
//echo "Field is ".$field."\n";
// if the field is set and not empty
if(isset($_POST[$field]) && $_POST[$field] != '') {
//echo "Field is: ".$field."\n".$field." is: ".$_POST[$field]."\n";
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "$field LIKE '%" . mysql_real_escape_string($_POST[$field]) . "%'
";
}
}
// builds the query
$query = "\"
SELECT *
FROM wp_ct_ad_client_db_table
";
// if there are conditions defined
$query_user_id = "user_id = ".$user_id."
\"";
array_push($conditions, $query_user_id);
if(count($conditions) > 0) {
// append the conditions
$query .= "WHERE " . implode(' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
echo "Query String: ".$query."\n";
//$result = $wpdb->get_results($query);
$my_query = $query;
echo "Test My Query Logic \n";
//$result = $wpdb->get_results("SELECT * FROM wp_ct_ad_client_db_table WHERE lastname LIKE '%A%' AND user_id = $user_id;");
//$result = $wpdb->get_results($my_query);
$result = $wpdb->get_results($my_query, A_ARRAY);
var_dump($result);
[/code snippet]
I have to create a dynamic query based on the value received by the user's input, the value of the variables are posted by GET
When I simply run this
$qry = "SELECT* FROM LAPTOP WHERE 1=1";
$resul = mysqli_query($qry);
retrieve($resul);
all the content of this table are displayed without any error,(retrieve function here displays all the results based on the query) but when I try to modify it like this, I get a blank page
$qry = "SELECT * FROM LAPTOP WHERE 1=1";
if(!empty($company))
{
$qry .= " AND company='$company'" ;
}
if(!empty($cpu))
{
$qry.= " AND cpu='$cpu' " ;
}
if(!empty($lifestyle))
{
$qry.= " AND lifestyle='$lifestyle' " ;
}
if(!empty($display))
{
$qry.= " AND display='$display'" ;
}
if(!empty($ram))
{
$qry.= " AND ram='$ram' " ;
}
if(!empty($HDD))
{
$qry.= " AND HDD='$HDD' " ;
}
echo $qry;
$result= mysqli_query($qry) || die(mysqli_error()) ;
retrieve($result) ;
$p = basename($_SERVER['REQUEST_URI']) ;
The result of echo $qry; is as expected, it displays this
SELECT * FROM LAPTOP WHERE 1=1 AND company='Asus' AND cpu='intel i3'
Is there a way to correct this? The reason I tried using WHERE 1=1 clause is that when all the variables are equal to NULL then the query returns all the rows from the table.
i guess you have no data in your database matched with your conditions . OR you have case sensitive with names.
example :
cpu='Intel i3' // with big I
cpu='intel I3' // with big I
cpu='intel i3' // double space.
OR if you have big string , think to use LIKE
$qry.= " AND cpu LIKE '%$cpu%' " ;
Is this a typo also ($resul_T_)?
$resul = mysqli_query($qry);
retrieve($resul);
How you managed to lose that 't' and later get it back? ;)
As others have pointed out it may simply be that your query does not match any records.
Anyway what I usually do in a similar case is put all the conditions in an array, and then implode the array with 'AND'. That way you don't have to bother with 1=1 and it doesn't matter whether you have 0, 1 or more conditions.
<?php
$qry = "SELECT * FROM LAPTOP";
$conditions = array();
$cpu = 'Intel';
$ram = '24GB';
if(!empty($cpu))
{
$conditions[] = "cpu='$cpu'";
}
if(!empty($lifestyle))
{
$conditions[] = "lifestyle='$lifestyle'";
}
if(!empty($display))
{
$conditions[] = "display='$display'";
}
if(!empty($ram))
{
$conditions[] = "ram='$ram'";
}
if(!empty($HDD))
{
$conditions[] = "HDD='$HDD'";
}
if( count( $conditions ) > 0 )
{
$qry .= " WHERE ";
$qry .= implode( " AND ", $conditions );
}
print_r($qry);
?>
When I run the following MySQL query via PHP and all of the elements of $_GET() are empty strings, all the records in the volunteers table are returned (for obvious reasons).
$first = $_GET['FirstName'];
$last = $_GET['LastName'];
$middle = $_GET['MI'];
$query = "SELECT * FROM volunteers WHERE 0=0";
if ($first){
$query .= " AND first like '$first%'";
}
if ($middle){
$query .= " AND mi like '$middle%'";
}
if ($last){
$query .= " AND last like '$last%'";
}
$result = mysql_query($query);
What is the most elegant way of allowing empty parameters to be sent to this script with the result being that an empty $result is returned?
my solution:
$input = Array(
'FirstName' => 'first',
'LastName' => 'last',
'MI' => 'mi'
);
$where = Array();
foreach($input as $key => $column) {
$value = trim(mysql_escape_string($_GET[$key]));
if($value) $where[] = "`$column` like '$value%'";
}
if(count($where)) {
$query = "SELECT * FROM volunteers WHERE ".join(" AND ", $where);
$result = mysql_query($query);
}
There's no point in running a (potentially) expensive query if there's nothing for that query to do. So instead of trying to come up with an alternate query to prevent no-terms being searched, just don't run the search at all if there's no terms:
$where = '';
... add clauses ...
if ($where !== '') {
$sql = "SELECT ... WHERE $where";
... do query ...
} else {
die("You didn't enter any search terms");
}
With your current code, if everything is empty, you will get the WHERE 0=0 SQL which is TRUE for all rows in the table.
All you have to do is remove the if statements...
I have a form that is going to be used to search through a table of support tickets.
the user can search from a few difficult optional fields.
Date (to/from)
Ticket Status
Engineer
Ticket Contact
I'm wondering what is the best way to deal with optional search filters. So I have a query that takes in parameters from the user. So if the user searches using both the from and to dates then the query would want to include BETWEEN. So do I have to write a different query for if the user searches for only from. or another query when the user has not added any date parameters? Then what if the status dropdown is blank? Is that another query?
Any help to clear this up would be great!
Jonesy
Build your query in parts. Start with whatever is constant in your query, and add on more SQL depending on what extra conditions:
$query = "SELECT ...
FROM ...
WHERE [where conditions that are always going to be present]";
if (isset($_POST['date_from']) && isset($_POST['date_to']))
{
$query .= ... // query code for dealing with dates
}
if (isset($_POST['status']))
{
$query .= ... // deal with status
}
// etc.
// Once you have your query fully built, execute it
$result_set = mysql_query($query);
This code is obviously just a skeleton, but that's how I would construct my query.
Hard to say without knowing what sort of DB abstraction you're using, but assuming you're hand-writing the SQL, it's fairly simple, just build up sections of your where clause individually for each variable. (Assuming here that your vars are already escaped/quoted.)
$where_clause = array();
if (!empty($date_from)) {
$where_clause[] = "table.date >= $date_from";
}
if (!empty($date_to)) {
$where_clause[] = "table.date <= $date_to";
}
if (!empty($status)) {
$where_clause[] = "status = $status";
}
$query = 'select * from table where ' . join(' and ', $where_clause);
This is an elegant way that I use alot and wish will help you too:
$q = 'SELECT * FROM Users';
$buildQ = array();
if (empty($idOrName) === false) {
$buildQ[] = '(userid = "' . $idOrName . '" OR username LIKE "%' . $idOrName. '%")';
}
if (empty($nickname) === false) {
$buildQ[] = 'nickname="' . $nickname . '"';
}
if (empty($salary) === false) {
$buildQ[] = 'salary="' . $salary . '"';
}
// ... any other criterias like above if statements
if (count($buildQ) === 1) {
$q .= ' WHERE ' . $buildQ[0];
} else if (count($buildQ) > 1) {
$count = 0;
foreach ($buildQ as $query) {
if ($count === 0) {
$q .= ' WHERE ' . $query;
} else {
$q .= ' AND ' . $query;
}
$count++;
}
}
I think it would be better if You generate query dynamically at runtime based on which fields are filled. So You could make some helper which appends specific query fragments if only one date is passed and the other one is null, or when both are passed and so on.
Ok, i have a problem here...
I am sending values of drop down lists via ajax to this PHP file.
Now I want to search a mysql database using these values, which I have managed to do, BUT, only if I set the values to something...
Take a look:
$query = "SELECT * FROM cars_db WHERE price BETWEEN '$cars_price_from' AND '$cars_price_to' AND year BETWEEN '$cars_year_from' AND '$cars_year_to' AND mileage BETWEEN '$cars_mileage_from' AND '$cars_mileage_to' AND gearbox = '$cars_gearbox' AND fuel = '$cars_fuel'";
now, what if the user doesnt select any "price_from" or "year_from"... The fields are only optional, so if the user doesnt enter any "price from" or "year from", then the user wants ALL cars to show...
Do I have to write a query statement for each case or is there another way?
I do something similar to davethegr8 except I put my conditions in an array and then implode at the end just so I don't have to worry about which conditions got added and whether I need to add extra AND's.
For example:
$sql = "SELECT * FROM car_db";
// an array to hold the conditions
$conditions = array();
// for price
if ($car_price_from > 0 && $car_price_to > $car_price_from) {
$conditions[] = "(price BETWEEN '$cars_price_from' AND '$cars_price_to')";
}
elseif ($car_price_from > 0) {
$conditions[] = "(price >= '$cars_price_from')";
}
elseif ($car_price_to > 0) {
$conditions[] = "(price <= '$cars_price_from')";
}
else {
//nothing
}
// similar for the other variables, building up the $conditions array.
// now append to the existing $sql
if (count($conditions) > 0){
$sql .= 'WHERE ' . implode(' AND ', $conditions);
}
You could simply detect which parameters are missing in your PHP code and fill in a suitable default. eg
if (!isset($cars_mileage_to))
$cars_mileage_to = 500000;
You can build you query, adding the "where" part only if your variables are different from "".
or if you're using mysql 5.x, you can also use subselects:
http://dev.mysql.com/doc/refman/5.0/en/subqueries.html
don't forget to validate the input. It's trivial with firebug, for example, to inject some tasty sql.