How to run MySQLi query dynamically - php

Is there any way to run mysqli query dynamically ? I am working on a small project who has dynamic form generation option. And then they want to filer those forms. Obviously we dont know how much will be form fields and how many filters they want. So is there any such way through which I can perform this action? Suppose if i can do something
SELECT * FROM table WHERE fld1 = 1 OR fld2 = 2 OR fld3 = 3....
Where those 1, 2, 3,... Can be something or maybe its empty depend on filters.

You can dynamically build your query in php by examining your $_POST values and then building out your where statement. Here's some pseudo code
foreach($_POST as $name=>$value)
{
$where[] = "`$key` = '$value'";
}
$sql = "SELECT * FROM table WHERE ".implode("OR", $where);
Of course you will need to either sanitize or use a prepared statement to make sure this is safe.

The best way to run it dynamically is by using PDO and classes, if youre confused about any of those two things check out the PHPGuru Jeffery Way found here: https://laracasts.com/series/php-for-beginners and check out his PHP tutorials, youll quickly learn what you need to do to be able to make a class that allows you to dynamically connect to your database!

Maybe do something like:
$Where = array();
foreach($_POST['form-field'] as $Field=>$Value){
if($Value){
$Where[] = $Field."=".$Value;
}
}
$Query = "SELECT * FROM table WHERE ".implode(" OR ",$Where);

You can use IN clause of in MySQL query.
Similar like this.
SELECT * FROM table
WHERE fld1 IN (1, 2, 3);
Hope this will help you.

$filter = '';
$filter .= 'fld1 = 1 OR ';
$filter .= 'fld2 = 2 OR ';
$filter .= 'fld3 = 3 OR ';
...
...
if(!empty($filter)) {
$filter = substr($filter,0,-2); // delete last OR
}
$query = "SELECT * FROM table WHERE ".$filter."";
...
Something like this would work, you have to modify the way you populate $filter
Hope this'll help.

Related

Append condition to current query [duplicate]

This question already has an answer here:
How to ignore a parameter in a prepared mysqli query in PHP?
(1 answer)
Closed 4 years ago.
For example, we have a mysqli query for select:
$sql = "SELECT * FROM table WHERE cat = 1";
And want to append some extra query to above query based on query string, I tried something like this: (This is just sample, not my Original code)
$keyw = $_GET["k"];
if($keyw){
$cleanKeyw = mysqli_real_escape_string($connection, $keyw);
$addQ= "AND name LIKE '%$cleanKeyw%' OR text LIKE '%$cleanKeyw%'";
} else {
$addQ= "";
}
$sql = "SELECT * FROM table WHERE cat = 1 $addQ";
Not this one, I almost have 10 more statment that want to append to current query
I want to add query if k query string is set, it works but I want to be sure, is it safe or right way to do this? because it's based on my logic and I'm newbie on php and don't know there is technical way to do this?
Also I want to know is there a way to do this via prepared statments ?
Unfortunately most answers to this will be too broad. There is no right or wrong way, and you have escaped your inputs (which is great).
You could consider building your wheres as an array, then imploding them together.
$wheres = [];
$wheres[] = 'cat = 1';
if ($keyw) {
// escape etc
$wheres[] = 'name LIKE '%$cleanKeyw%' OR text LIKE '%$cleanKeyw%''
}
$wheres = implode(" AND ", $wheres);
$sql = "SELECT * FROM table WHERE $wheres";
You could then add lots more $wheres[] as you go along.

Updating from Pear DB to Pear MDB2 - what is the developer trying to do in the query?

I'm updating a site from pear DB to MDB2, I've managed to get quite far but I've come unstuck on a query I'm not sure what they are trying to achieve here.
Can anyone explain.
Here it is
$bookRes = $mdb2->query(("SELECT * FROM book WHERE (".join(' OR ', $sqlParams).") $categorySQL ORDER BY title"), $sqlValues);
while ($row = $bookRes->fetchRow()) {
$row['type'] = 'book';
$booksPossibles[] = $row;
}
I would need to see a bit more of the code to be sure, but this appears to be a simple dynamic generation of a SELECT statement where various criteria, with placeholders, stored in the $sqlParams array are being added to the WHERE clause and the values for those criteria are specified in the $sqlValues variable, again presumably an array.
so $sqlParams and $sqlValues might look like:
$sqlParams = array("val1 > ?", "val2 = ?");
$sqlValues = array(2, 4);
(It helps to know that the join keyword in PHP is just an alias for implode.)

PHP - building query for table filters

I need help with building a query, I have a form ( multiple dropdowns) and need to display a data table according to the user selection.
filters.php (on server side - ajax )
$criteria[0] = $_POST['Size'];
$criteria[1] = $_POST['Name'];
$criteria[2] = $_POST['Color'];
$criteria[3] = $_POST['Sku'];
$criteria[4] = $_POST['Features'];
$statement = $dbh->prepare("select * from table_name where Sku = :sku AND Size = :size AND Color = :color AND Features LIKE :features ");
$statement->execute(array(':name' => $criteria[1], ':Size'=> $criteria[0], ':color'=>$criteria[2], ':sku'=>$criteria[3], ':features'=> '%'.$features[4].'%'));
$statement->setFetchMode(PDO::FETCH_ASSOC);
$subrows = $statement->fetchAll();
// ect..
When all the criteria are selected ( all dropdowns have a value ) the call will return data , but what if the user only selects one, two or three dropdowns? It will return an empty table which is logic if using the query above.
I was thinking maybe I should try first to check if the variables are set, then perform for each scenario a query ? Im kind of lost how to implement it.
The idea is to have a small div with dropdowns next to the data table which allows filtering.
thanks
If statements dependent on the $_POST key may be the best way - and add the corresponding part to the query string:
i.e. :
$queryString = "select * from table_name where ";
if($_POST['SKU']){
$queryString .= "Sku = :sku";
}
Furthermore, to handle the "AND" parts :
$and = (count($_POST) > 1 ? 1 : 0);
and inside each if statement, the first line should be:
$queryString .= ($and ? "AND " : "");
Furthermore, I would suggest using an ORM, (Idiorm being my personal favorite, which I use in this example: )
$queryBuilder = ORM::for_table("table");
if($_POST['Sku'])
$queryBuilder = $queryBuilder->where("Sku", $_POST['Sku']);
and so on and so forth.
Check the desired variables to see if they contain data, if so you have to build the query. You can add to the array at the same time! For example:
$myarray = array();
if(!empty($criteria[0])){
$myarray["Size"] = $criteria[0];
}

PHP MYSQL syntax

I'm having a little trouble with my MYSQL query
I have a DB full of products and I have a dropdown menu which lets a user select what time of day they'd like to get get results for :-
Dropdown
Breakfast
Lunch
Evening
Anytime
At the moment my statement is
SELECT * from DEALS WHERE timeofday='post data from form';
Now this works fine, but with the option for 'Anytime' I'd like the query to be able to search for results of all/any of the above.
I was thinking of perhaps doing an IF statement which fires off 2 separate queries, one which says if the $_POST['timeofday'] == 'Anytime' then fire off
SELECT * from DEALS where timeofday='Breakfast'
OR timeofday='Lunch' OR timeofday='Evening';
otherwise just do the normal query, although wondered if it was possible to do this in just one statement.
Kind regards
$query = 'SELECT * from DEALS';
if ($_POST['timeofday'] != 'Anytime') {
$query .= ' WHERE timeofday="' . $_POST['timeofday'] . '"';
}
As DCoder mentioned, this approach is vulnerable to sql injection... You should check/sanitize the input or use prepared statements. In this case where there is a predefined set of values you can:
$knownTimesOfDay = array('Breakfast', 'Lunch', 'Evening', 'Anytime');
if (!in_array($_POST['timeofday'])) {
die('Unsuppotred time of day... Did it really come from the form?');
}
$query = 'SELECT * from DEALS';
if ($_POST['timeofday'] != 'Anytime') {
$query .= ' WHERE timeofday="' . $_POST['timeofday'] . '"';
}
Don't think it can be done in one statement.
You are going to have to use an if statement anyhow.
if these are the only 3 possible values for timeofday,then you can have an if in the php script like this:
if($_POST['timeofday'] != 'Anytime' )
sql .= "where timeofday='".$_POST['timeofday']."'";
This could turn out to be negative depending on the items you have in the table, but you could use:
SELECT * from DEALS where timeofday LIKE '%{$post_data}%'
It would return all the results from timeofday if $post_data was an empty string.

PHP/MYSQL advanced search script. How?

I need some guidance to make an advanced search script for a website I'm working on.
I already know how to search the database for simple queries. The problem I'm encountering right now is how to search, when using multiple select boxes. For example:
This is just a simple form with different search options. The question is:
The visitor can choose to search on a country or city, both or even with all three options.
How do I catch that in the PHP script? Do I have to check if for example a city has been chosen, and fire a query based on that? But if I do that I would have to make different queries based on each select option.
In pseudo-code it would be something like this: (I imagine)
if country and city and something else is not null, launch a query to search in all three tables in the database.
But what to do when just the country has been chosen? Or just the city?
Is there a simple way to accomplish this?
Thanks in advance.
I like using an array to join conditions so I don't have to worry about leading or trailing AND's.
$conditions = array();
if ($formCondition1) {
$conditions[] = 'state = "'.$somevalue.'"';
}
if ($formCondition2) {
$conditions[] = 'country = "'.$somevalue.'"';
}
...
if ($formConditionN) {
$conditions[] = 'N = "'.$somevalue.'"';
}
//finally join the conditions together, the simplest case is with ANDs (if you need to add ORs, which it sounds like you don't, then this code would be a bit more complex)
$sqlStatement = 'SELECT field1, field2 FROM tableABC WHERE '.implode(' AND ', $conditions);
EDIT: don't forget to escape the input to prevent injection attacks, and of course test to make sure there are at least 1 condition before running the query.
EDIT: lol jswolf and I think very much alike :)
I make a $where array, add my conditions to it as necessary, and then implode it with ' AND ' as the glue. So something like:
$where = array();
if $city is defined
$where[] = "city = '".mysql_real_escape_string($city)."'";
fi
if $country is defined
$where[] = "country = '".mysql_real_escape_string($country)."'";
fi
...
if(count($where)) {
$query.= ' WHERE '.implode(' AND ', $where);
}
I would try something like:
$qry = "SELECT * FROM table WHERE ";
if ($country != '') {
$qry .= "country='".mysql_real_escape_string($country)."' AND "
}
if ($city != '') {
$qry .= "city='".mysql_real_escape_string($city)."' AND "
}
$qry .= '1';
$res = mysql_query($qry);
The query is built up depending on what is set. Note the "1" on the end of the query string which is always true. This is needed to follow the "WHERE" if $country and $city are both empty, or to follow the last "AND" if they are not.

Categories