I have a prepared mysqli query like this:
$query = $database->prepare("SELECT * FROM items WHERE inStock > ? AND size < ? AND name LIKE ?");
$query->bind_param('iis', $inStock, $size, $name);
$query->execute();
There are many various conditions in the WHERE clause which filter out the results.
The problem is, that those parameters are supplied in a search form and they aren't mandatory. For example, someone can search by using only the name, or only by using the size and name, or by using the size, name and inStock, all at the same time.
I need some way to adjust the query so I can supply only the parameters I want. The only solution I can think of, is to make a huge if..else structure where prepared queries with all combinations of the search options exist, but that is out of the question as there are thousands of combinations.
The only actual realistic solution I can think of, would be to use a not prepared query, where I glue the conditions together with from pieces like $query .= "AND name LIKE '%".escapestuff($_POST['name'])."%'"
But that is very ugly and I would very much like to stay with the prepared query system.
You can build up a list of the criteria and add into a list the bind values and types, here is a quick mock up which uses two of the fields you refer to...
$data = [];
$params = "";
$where = [];
if ( !empty($name)) {
$data[] = $name;
$params.="s";
$where[] = "name like ?";
}
if ( !empty($size)) {
$data[] = $size;
$params.="i";
$where[] = "size < ?";
}
$sql = "SELECT * FROM items";
if ( count($where) > 0 ){
$sql .= " where ". implode ( " and ", $where);
}
$query = $database->prepare($sql);
$query->bind_param($params, ...$data);
$query->execute();
Notice that the bind_param() uses the ... to allow you to pass an array instead of the individual fields.
Related
This question already has an answer here:
PDO pagination with LIKE
(1 answer)
Closed 2 years ago.
I have one doubt about PDO.
I have a method in the class that returns data from the database for sent filters.
I want to get a number of rows for that query, but there are LIMIT and STAR in the query.
So because of that, I am using two queries to get a number of rows and data but to work, I need to bind the same value two times. Is there any more elegant way to achieve not have repeated code?
The method that I use is below.
$db = $this->openConnection();
$sql = " SELECT * FROM contacts";
// Filter data by main search input
if(!empty($search_query)){
$sql .= " WHERE ( location LIKE :search_query_location OR address LIKE :search_query_address ) ";
}
$sql .=" ORDER BY ".$order;
$stmt = $db->prepare($sql);
if(!empty($search_query)){
$stmt->bindValue(':search_query_location', (string) $search_query.'%');
$stmt->bindValue(':search_query_address', (string) $search_query.'%');
}
// Get number of rows after filter
$stmt->execute();
$total = $stmt->rowCount();
$sql .=" LIMIT :start, :limit_num";
$stmt = $db->prepare($sql);
if(!empty($search_query)){
$stmt->bindValue(':search_query_location', (string) $search_query.'%');
$stmt->bindValue(':search_query_address', (string) $search_query.'%');
}
// Bind start and limit value
$stmt->bindValue(':start', (int) $start, PDO::PARAM_INT);
$stmt->bindValue(':limit_num', (int) $limit, PDO::PARAM_INT);
// Get filtered data
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
return array($total,$data);
WHY I NEED TO REPEAT BINDING FOR TWO SAME QUERIES ONE WITHOUT LIMITS TO WORK IS THERE ANY ELEGANT SOLUTION
Problem
The reason that you have to bind twice is that $pdo->prepare($sql) returns a PDOStatement which isn't editable after it's been set. So when you update it you have to overwrite it and start again... Obviously the new statement doesn't retain the old bound parameters.
If you think of it as an array that you add some data to and then overwrite with a new, blank, array... You then can't read the information from the original array because it doesn't exist in the new one:
$array = [];
$array[] = 1;
$array[] = 2;
$array[] = 3;
var_dump($array);
/*
Output...
Array
(
[0] => 1
[1] => 2
[2] => 3
)
*/
$array = [];
print_r($array);
/*
Output...
Array
(
)
*/
The difference is that PDOStatement is an object not an array. But it's functionally the same thing!
N.B.
While $pdo->rowCount() may return the number of results from a SELECT query it isn't guaranteed so usually it's best practice not to use it.
I wouldn't overwrite the variable with a new query anyway... Better to use a different variable name e.g. $countQuery and $dataQuery
Solutions
So, if the only reason is that you're trying to reduce the amount of code then there are a bunch of solutions that you could use. However, this doesn't appear to be code golf, so why does it matter?
Solution 1
Assuming you don't have an unreasonable amount of unneeded results returned by the query then you could just return the array from the first query and use array_slice to take the place of the second query...
$pdo = $this->openConnection();
$sql = "SELECT * FROM contacts";
if($search_query){
$sql .= " WHERE ( location LIKE :search_query_location OR address LIKE :search_query_address ) ";
}
$sql .= " ORDER BY :order";
$query = $pdo->prepare($sql);
if($search_query){
$query->bindValue(':search_query_location', $search_query.'%');
$query->bindValue(':search_query_address', $search_query.'%');
}
$query->bindValue(':order', $order);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
$count = count($result);
return [$count, array_slice($result, $start, $limit)];
Solution 2
If you're worried about readability and code maintenance then you should remember that: it's usual for a method/function to have a reasonably specific function, for example...
Return the number of rows which match a query
Return the data which matches a query
Implementing this would mean you have each of your queries in separate functions:
function countContacts(...)
{
$sql = 'SELECT count(*) FROM contacts WHERE ...';
$query = $pdo->prepare($sql);
$query->bindValue(...);
$query->execute();
return $query->fetchColumn();
}
function getContacts(...)
{
$sql = 'SELECT * FROM contacts WHERE ... ORDER BY ... LIMIT ...';
$query = $pdo->prepare($sql);
$query->bindValue(...);
$query->execute();
return $result->fetchAll(PDO::FETCH_ASSOC);
}
Solution 3
I wouldn't use this, but it technically solves the issue
You could use a union and run two queries in one, then you could use emulated prepared statements (as per #Straberry's answer) to bind once...
Although, again, emulated prepared statements are not something that anyone on here is likely to suggest you should use without good reason. Of course you could use normal prepares and use different bind parameter names.
Either way, this isn't a great solution. I wouldn't use it.
$sql = "
SELECT COUNT(*) as col1, null as col2, null as col3, null as col4, null as col5 FROM contacts WHERE ...
UNTION
SELECT col1, col2, col3, col4, col5 FROM contacts WHERE ... ORDER BY ... LIMIT ...
";
$query = $pdo->prepare($sql);
$query->bindValue(...);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
return [$result[0]["col1"], array_slice($result, 1)];
I have a prepared mysqli query like this:
$query = $database->prepare("SELECT * FROM items WHERE inStock > ? AND size < ? AND name LIKE ?");
$query->bind_param('iis', $inStock, $size, $name);
$query->execute();
There are many various conditions in the WHERE clause which filter out the results.
The problem is, that those parameters are supplied in a search form and they aren't mandatory. For example, someone can search by using only the name, or only by using the size and name, or by using the size, name and inStock, all at the same time.
I need some way to adjust the query so I can supply only the parameters I want. The only solution I can think of, is to make a huge if..else structure where prepared queries with all combinations of the search options exist, but that is out of the question as there are thousands of combinations.
The only actual realistic solution I can think of, would be to use a not prepared query, where I glue the conditions together with from pieces like $query .= "AND name LIKE '%".escapestuff($_POST['name'])."%'"
But that is very ugly and I would very much like to stay with the prepared query system.
You can build up a list of the criteria and add into a list the bind values and types, here is a quick mock up which uses two of the fields you refer to...
$data = [];
$params = "";
$where = [];
if ( !empty($name)) {
$data[] = $name;
$params.="s";
$where[] = "name like ?";
}
if ( !empty($size)) {
$data[] = $size;
$params.="i";
$where[] = "size < ?";
}
$sql = "SELECT * FROM items";
if ( count($where) > 0 ){
$sql .= " where ". implode ( " and ", $where);
}
$query = $database->prepare($sql);
$query->bind_param($params, ...$data);
$query->execute();
Notice that the bind_param() uses the ... to allow you to pass an array instead of the individual fields.
This question already has answers here:
Can I bind an array to an IN() condition in a PDO query?
(23 answers)
Closed 1 year ago.
I'm reworking some PHP code to use PDO for the database access, but I'm running into a problem with a "WHERE... IN" query.
I'm trying to delete some things from a database, based on which items on a form are checked. The length and content of the list will vary, but for this example, imagine that it's this:
$idlist = '260,201,221,216,217,169,210,212,213';
Then the query looks like this:
$query = "DELETE from `foo` WHERE `id` IN (:idlist)";
$st = $db->prepare($query);
$st->execute(array(':idlist' => $idlist));
When I do this, only the first ID is deleted. (I assume it throws out the comma and everything after it.)
I've also tried making $idlist an array, but then it doesn't delete anything.
What's the proper way to use a list of items in a PDO prepared statement?
Since you can't mix Values (the Numbers) with control flow logic (the commas) with prepared statements you need one placeholder per Value.
$idlist = array('260','201','221','216','217','169','210','212','213');
$questionmarks = str_repeat("?,", count($idlist)-1) . "?";
$stmt = $dbh->prepare("DELETE FROM `foo` WHERE `id` IN ($questionmarks)");
and loop to bind the parameters.
This may be helpful too:
https://phpdelusions.net/pdo#in
$arr = [1,2,3];
$in = str_repeat('?,', count($arr) - 1) . '?';
$sql = "SELECT * FROM table WHERE column IN ($in)";
$stm = $db->prepare($sql);
$stm->execute($arr);
$data = $stm->fetchAll();
I would make $idlist and array, then simply loop through the array using foreach to delete the specific item.
$idlist = array('260','201','221','216','217','169','210','212','213');
$stmt = $dbh->prepare("DELETE FROM `foo` WHERE `id` = ?");
$stmt->bindParam(1, $id);
foreach ($idlist as $item){
$id = $item;
$stmt->execute();
}
I am converting all my queries from mysql to PDO, and in this process I found a conditional query like a follows
if (isset($parameters['searchTerm'])) {
$where =" And title LIKE '%{$parameters['searchTerm'] }%'";
}
$sql = "Select * from table data Where tableId = 5 {$where} ";
and when I am trying to convert this query in PDO the expected syntax is as follows
if (isset($parameters['searchTerm'])) {
$where =" And title LIKE :searchTerm";
}
$sql = $dbh->prepare("Select * from table data Where tableId = 5 {$where}");
if (isset($parameters['searchTerm'])) {
$sql ->bindParam(':searchTerm', '%{$parameters['searchTerm'] }%');
}
$sql ->execute();
Now as you can See that the if condition if (isset ($parameters ['searchTerm'] )) {...} is repeated twice.
The reason is
I can not prepare the sql query before $where is being set thus $sql variable is initialized after first if statement
I can not bind the parameters until I prepare the sql so it has to be placed after the $sql is being prepared
So there is one if statement before $sql = $dbh->prepare("Select * from table data Where tableId = 5 {$where}"); and one if statement after.
And my question is: Is there a way to remove this redundant if statement or I have to do it this way only.
you can use handy PDO's feature that lets you to send array with parameters straight into execute()
$where = '';
$params = array();
if (isset($parameters['searchTerm'])) {
$where =" And title LIKE :searchTerm";
$params['searchTerm'] = "%$parameters[searchTerm]%";
}
$sql = "Select * from table data Where tableId = 5 $where";
$pdo->prepare($sql)->execute($params);
Note that PHP syntax in your code is also wrong.
I have four possible variables, only one of them is required. My question is, how do I prepare a statement / construct the sql query if there parts of the query that may or not show up.
Something like this, I guess:
sql = "SELECT * FROM dogs WHERE name = ?"
if(isset($dogid)) {
sql .= "AND WHERE id = ?";
}
}
if(isset($dogcolour)) {
sql .= "AND WHERE colour = ?";
}
My brain is totally broken, and I figure there has to be a better way to prepare it than using something like $dogID = "true"; in each if, and then binding it at the end with a bunch of if statements.
Well I would define some empty value, and then check everything in database.
$sql = "SELECT * FROM dogs WHERE (IF(? = 0, 1 = 1, name = ?)) AND (IF(? = 0, 1 = 1, colour = ?))"
this solution has one drawback, you need to pass all parameters twice:
$statement->bind_param('ssss', $name, $name, $colour, $colour);
if name or $colour variable is 0 then 1 = 1 is executed in where statement (witch is always true). There should be posibility to pass NULL value to mysqli, however for me it doesn't work, if it work then could be possible to simplify query.
$sql = "SELECT * FROM dogs WHERE name = (IFNULL(?, name)) AND colour = (IFNULL(?, colour))"