Combine two if conditions - php

Im a new and just learning php. I have a data table with search boxes with this code.
$condition = '';
if(isset($_REQUEST['username']) and $_REQUEST['username']!="") {
$condition .= ' AND username LIKE "%'.$_REQUEST['username'].'%" ';
}
if(isset($_REQUEST['useremail']) and $_REQUEST['useremail']!=""){
$condition .= ' AND useremail LIKE "%'.$_REQUEST['useremail'].'%" ';
}
What I need is to search with both username AND useremail. I have attempted everything I know and spent a few hours searching for a solution but with no success.

You could write a complicated set of IF's with equals and not equals tests all over the place, but as the list of test gets bigger the IF's get almost impossible to maintain or understand. So it might be simpler to just build and array of things to AND in the query
$condition = '';
$and = []; #init the array
if(isset($_REQUEST['username']) and $_REQUEST['username']!="") {
$and[] = ['name' => 'username', 'value' => $_REQUEST['username'] ];
}
if(isset($_REQUEST['useremail']) and $_REQUEST['useremail']!=""){
$and[] = [''name' => 'useremail', 'value' => $_REQUEST['useremail'] ];
}
#now build the condition string
foreach ($and as $i => $andMe) {
if ( $i != 0 ){
// AND required here
$condition .= ' AND ';
}
$condition .= $andMe['name'] . ' = ' . $andMe['value'];
}
Also I have replaced the LIKE with an = as it seems more appropriate, I assume you dont ask people to enter something a bit like there user name and email, but in fact ask for the actual username or email
Of course that would still be susceptible to SQL Injection Attack So a better solution would be
#now build the condition string
foreach ($and as $i => $andMe) {
if ( $i != 0 ){
// AND required here
$condition .= ' AND ';
}
$condition .= $andMe['name'] . ' = ?';
}
And then prepare the query and use the value part to bind to the parameters.

Issue is you have leading AND in your query.
push condition to array then join conditions.
like that
$condition_array = [];
if(isset($_REQUEST['username']) and $_REQUEST['username']!="") {
$condition_array[] = 'username LIKE "%'.$_REQUEST['username'].'%" ';
}
if(isset($_REQUEST['useremail']) and $_REQUEST['useremail']!=""){
$condition_array[] = 'useremail LIKE "%'.$_REQUEST['useremail'].'%" ';
}
$condition = implode(" AND ",$condition_array);

You can create an array of all the keys that are to be searched. Then, create a new array and collect all conditions. Implode them in the end with AND as the glue. This way, query is made correctly without needing to add 100 different if conditions.
Use PDO objects to avoid SQL injection attacks. In the below snippet, if you ever need to add 1 more column for search, just add it in the below $keys array and rest works as usual without needing any further refactoring.
Snippet:
<?php
$keys = ['username', 'useremail'];
$conditions = [];
$placeholders = [];
foreach($keys as $key){
if(!empty($_REQUEST[ $key ])){
$conditions = " $key LIKE ?";
$placeholders[] = '%' . $_REQUEST[ $key ] . '%';
}
}
// you need to create $mysqli object here
if(count($conditions) === 0){
$stmt = $mysqli->prepare('select * from table');
$stmt->execute();
// rest of your code
}else{
$stmt = $mysqli->prepare('select * from table where '. implode(" AND ", $conditions));
$stmt->bind_param(str_repeat('s', count($placeholders)), ...$placeholders);
$stmt->execute();
// rest of your code
}

Related

Problem with binding NULL value to named placeholders with associative array in execute function in PDO

I am trying to construct and execute a delete query when the table_name and the conditional_clauses are passed as parameters in OOP fashion. I am using PDO by wrapping it in a custom wrapper. I am using prepared statements, with named placeholders. In every case, I am passing an associative array inside PDO->execute() function, where the array_keys are the name of the placeholders used and the array_value are the corresponding values to be substituted. I am facing issues only in one case when I want to specify an IS NULL condition with WHERE clause.
Basically, if I want to search for something like:
SELECT * FROM EMPLOYEES WHERE salary > 10000 AND skill IS NULL
I am able to dynamically construct a prepared statement which looks like:
$sql = SELECT * FROM employees WHERE salary > :salary AND skill IS :skill
And then execute the prepared SQL as:
$stmt->execute(["salary" => 10000,
"skill" => null])
This is where I am facing the issue. I am getting a fatal error here only when a value is null. And, I want to include checking for IS NULL functionality in my wrapper.
Please note -
I want to achieve the purpose without using bindValue() or
bindParam() functions.
I have turned emulation off (as MySQL can sort all placeholders out
properly).
Using ? as placeholders isn't an option for me. I'll have to
re-design my entire codebase otherwise.
Here's the code snippet for reference:
<?php
class DeleteQuery {
protected function where(array $whereCondition, array &$values): string{
$whereClause = ' WHERE ';
$i = 0;
$j = 0;
$hasComparators = array_key_exists("comparators", $whereCondition);
$hasConjunctions = array_key_exists("conjunctions", $whereCondition);
$comparatorCount = $hasComparators ? count($whereCondition["comparators"]) : 0;
$conjunctionCount = $hasConjunctions ? count($whereCondition["conjunctions"]) : 0;
foreach ($whereCondition["predicates"] as $predicate_key => &$predicate_value) {
$whereClause .= $predicate_key;
$whereClause .= ($hasComparators and ($i < $comparatorCount)) ?
' ' . $whereCondition["comparators"][$i++] . ' ' : ' = ';
if (is_array($predicate_value)) {
$whereClause .= "('" . implode("', '", $predicate_value) . "')";
unset($whereCondition['predicates'][$predicate_key]);
} else {
$whereClause .= ':' . $predicate_key;
}
$whereClause .= !($hasConjunctions and ($j < $conjunctionCount)) ?
'' : ' ' . $whereCondition["conjunctions"][$j++] . ' ';
}
$values = array_merge($values, $whereCondition['predicates']);
return $whereClause;
}
public function delete($tblName, $conditions) {
$sql = "DELETE FROM " . $tblName;
$values = [];
if (!empty($conditions) && is_array($conditions)) {
/* If the stmt has WHERE clause */
if (array_key_exists("where", $conditions)) {
$sql .= $this->where($conditions['where'], $values);
}
/* If the stmt has ORDER BY clause */
if (array_key_exists("order_by", $conditions)) {
$sql .= $this->order_by($conditions['order_by']);
}
/* If the stmt has LIMIT clause */
if (array_key_exists("limit", $conditions)) {
$sql .= $this->limit($conditions['limit'], $values);
}
}
echo $sql . PHP_EOL;
print_r($values);
}
}
$deleteConditions = [
"where" => array(
"predicates" => ["skill" => null],
"comparators" => ["IS"],
),
/* other conditional clauses */
];
$obj = new DeleteQuery();
$obj->delete("employees", $deleteConditions);
The IS operator can't be used with an expression. IS NULL and IS NOT NULL are keywords.
You need a test that works with both null and non-null values of :skill. You can use the null-safe equality operator, <=>
$sql = 'SELECT *
FROM employees
WHERE salary > :salary
AND skill <=> :skill';

How can I dynamically build a parameterized query for RedBeanPHP 4?

So I have some data coming in via POST from a form with a large number of checkboxes and I'm trying to find records in the database that match the options checked. There are four sets of checkboxes, each being sent as an array. Each set of checkboxes represents a single column in the database and the values from the checked boxes are stored as a comma-delimited string. The values I'm searching for will not necessarily be consecutive so rather than a single LIKE %value% I think I have to break it up into a series of LIKE statements joined with AND. Here's what I've got:
$query = "";
$i = 1;
$vals = [];
foreach($_POST["category"] as $val){
$query .= "category LIKE :cat".$i." AND ";
$vals[":cat".$i] = "%".$val."%";
$i++;
}
$i = 1;
foreach($_POST["player"] as $val){
$query .= "player LIKE :plyr".$i." AND ";
$vals[":plyr".$i] = "%".$val."%";
$i++;
}
$i = 1;
foreach($_POST["instrument"] as $val){
$query .= "instrument LIKE :inst".$i." AND ";
$vals[":inst".$i] = "%".$val."%";
$i++;
}
$i = 1;
foreach($_POST["material"] as $val){
$query .= "material LIKE :mat".$i." AND ";
$vals[":mat".$i] = "%".$val."%";
$i++;
}
$query = rtrim($query, " AND ");
$tubas = R::convertToBeans("tuba", R::getAll("SELECT * FROM tuba WHERE ".$query, $vals));
This does seem to work in my preliminary testing but is it the best way to do it? Will it be safe from SQL injection?
Thanks!
As long as you use parameterized queries (like you do), you should be safe from SQL injection. There are edge cases though, using UTF-7 PDO is vulnerable (I think redbean is based on PDO)
I would change the code to something like this, minimizes the foreach clutter.
$query = 'SELECT * FROM tuba';
$where = [];
$params = [];
$checkboxes = [
'category',
'player',
'instrument',
'material'
];
foreach ($checkboxes as $checkbox) {
if (!isset($_POST[$checkbox])) {
// no checkboxes of this type submitted, move on
continue;
}
foreach ($_POST[$checkbox] as $val) {
$where[] = $checkbox . ' LIKE ?';
$params[] = '%' . $val . '%';
}
}
$query .= ' WHERE ' . implode($where, ' AND ');
$tubas = R::convertToBeans('tuba', R::getAll($query, $params));

Loop through an array to create an SQL Query

I have an array like the following:
tod_house
tod_bung
tod_flat
tod_barnc
tod_farm
tod_small
tod_build
tod_devland
tod_farmland
If any of these have a value, I want to add it to an SQL query, if it doesnt, I ignore it.
Further, if one has a value it needs to be added as an AND and any subsequent ones need to be an OR (but there is no way of telling which is going to be the first to have a value!)
Ive used the following snippet to check on the first value and append the query as needed, but I dont want to copy-and-paste this 9 times; one for each of the items in the array.
$i = 0;
if (isset($_GET['tod_house'])){
if ($i == 0){
$i=1;
$query .= " AND ";
} else {
$query .= " OR ";
}
$query .= "tod_house = 1";
}
Is there a way to loop through the array changing the names so I only have to use this code once (please note that $_GET['tod_house'] on the first line and tod_house on the last line are not the same thing! - the first is the name of the checkbox that passes the value, and the second one is just a string to add to the query)
Solution
The answer is based heavily upon the accepted answer, but I will show exactly what worked in case anyone else stumbles across this question....
I didnt want the answer to be as suggested:
tod_bung = 1 AND (tod_barnc = 1 OR tod_small = 1)
rather I wanted it like:
AND (tod_bung = 1 OR tod_barnc = 1 OR tod_small = 1)
so it could be appended to an existing query. Therefore his answer has been altered to the following:
$qOR = array();
foreach ($list as $var) {
if (isset($_GET[$var])) {
$qOR[] = "$var = 1";
}
}
$qOR = implode(' OR ', $qOR);
$query .= " AND (" .$qOR . ")";
IE there is no need for two different arrays - just loop through as he suggests, if the value is set add it to the new qOR array, then implode with OR statements, surround with parenthesis, and append to the original query.
The only slight issue with this is that if only one item is set, the query looks like:
AND (tod_bung = 1)
There are parenthesis but no OR statements inside. Strictly speaking they arent needed, but im sure it wont alter the workings of it so no worries!!
$list = array('tod_house', 'tod_bung', 'tod_flat', 'tod_barnc', 'tod_farm', 'tod_small', 'tod_build', 'tod_devland', 'tod_farmland');
$qOR = array();
$qAND = array();
foreach ($list as $var) {
if (isset($_GET[$var])) {
if (!empty($qAND)) {
$qOR[] = "$var = 1";
} else {
$qAND[] = "$var = 1";
}
$values[] = $_GET[$var];
}
}
$qOR = implode(' OR ', $qOR);
if ($qOR != '') {
$qOR = '(' . $qOR . ')';
}
$qAND[] = $qOR;
$qAND = implode(' AND ', $qAND);
echo $qAND;
This will output something like tod_bung = 1 AND (tod_barnc = 1 OR tod_small = 1)
As the parameter passed to $_GET is a string, you should build an array of strings containing all the keys above, iterating it and passing the values like if (isset($_GET[$key])) { ...
You could then even take the key for appending to the SQL string.
Their are a lot of ways out their
$list = array('tod_house', 'tod_bung', 'tod_flat', 'tod_barnc', 'tod_farm', 'tod_small', 'tod_build', 'tod_devland', 'tod_farmland');
if($_GET){
$query = "";
foreach ($_GET as $key=>$value){
$query .= (! $query) ? " AND ":" OR ";
if(in_array($key,$list) && $value){
$query .= $key." = '".$value."'";
}
}
}
Sure you have to take care about XSS and SQL injection
If the array elements are tested on the same column you should use IN (...) rather than :
AND ( ... OR ... OR ... )
If the values are 1 or 0 this should do it :
// If you need to get the values.
$values = $_GET;
$tod = array();
foreach($values as $key => $value) {
// if you only want the ones with a key like 'tod_'
// otherwise remove if statement
if(strpos($key, 'tod_') !== FALSE) {
$tod[$key] = $value;
}
}
// If you already have the values.
$tod = array(
'tod_house' => 1,
'tod_bung' => 0,
'tod_flat' => 1,
'tod_barnc' => 0
);
// remove all array elements with a value of 0.
if(($key = array_search(0, $tod)) !== FALSE) {
unset($tod[$key]);
}
// discard values (only keep keys).
$tod = array_keys($tod);
// build query which returns : AND column IN ('tod_house','tod_flat')
$query = "AND column IN ('" . implode("','", $tod) . "')";

Running PHP search script with empty parameters returns entire MySQL table

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...

Generating SQL query based on URL parameters

Suppose my URL is http://something.com/products.php?brand=samsung&condition=new
For the above query I am using isset() and $_GET[]) functions along with lots of if-else statements in PHP to generate a sql query for displaying the products which satisfy the search criteria.
For example: if I am dealing with only brand and condition parameters then this is how I will generate the query:
$sql = "select * from products where 1=1 ";
if(isset($_GET['brand']))
{
if(isset($_GET['condition']))
{
$sql = $sql + "and brand=".$_GET['brand']." and condition=".$_GET['condition'];
}
}
else
{
if(isset($_GET['condition']))
{
$sql = $sql + "and condition=".$_GET['condition'];
}
else
{
$sql = $sql + ";";
}
}
Now suppose my URL is having 10 parameters (or more). In this case, using if-else is not at all good. How can I generate the query without using so many if-else statements? Is there any better method/script/library available for doing this thing?
There are a number of ways to do this, but the easiest way would be to loop through the acceptable columns and then append appropriately.
// I generally use array and implode to do list concatenations. It avoids
// the need for a test condition and concatenation. It is debatable as to
// whether this is a faster design, but it is easier and chances are you
// won't really need to optimize that much over a database table (a table
// with over 10 columns generally needs to be re-thought)
$search = array();
// you want to white-list here. It is safer and it is more likely to prevent
// destructive user error.
$valid = array( 'condition', 'brand' /* and so on */ );
foreach( $valid as $column )
{
// does the key exist?
if( isset( $_GET[ $column ] ) )
{
// add it to the search array.
$search[] = $column . ' = ' . mysql_real_escape_string( $_GET[ $column ] );
}
}
$sql = 'SELECT * FROM TABLE_NAME WHERE ' . implode( ' AND ', $search );
// run your search.
If you really are trying to get rid of the 'if' statements, you could use this:
$columns = array_intersect( $valid, array_keys( $_GET ) );
foreach( $columns as $column )
{
$search[] = $column . ' = ' . mysql_real_escape_string( $_GET[ $column ] );
}
$sql = 'SELECT * FROM TABLE_NAME WHERE ' . implode( ' AND ', $search );
But you may want to run actual benchmarks to determine whether that is a substantially better option.

Categories