i’m working on a search form that handles multiple input forms. When only one search criteria is inserted, if works fine. But when two is used, it doesn’t. i see the flaw but i don’t know how to solve it. I’ve tried loops etc, but the problem still remains.
$sql = 'SELECT product_id, product_title FROM product WHERE ';
$where = array();
$values = array();
$types = '';
if (!empty($_GET['searchText'])) {
$where[] = 'product_title = ?';
$values[] = $_GET['searchText'];
$types .= 's';
}
if (!empty($_GET['searchCategorySelect'])) {
$where[] = 'product_categoryid = ?';
$values[] = $_GET['searchCategorySelect'];
$types .= 's';
}
$sql .= implode(' AND ',$where);
$search_stmt = $mysqli->prepare($sql);
$values = implode("", $values);
$search_stmt->bind_param($types, $values);
$search_stmt->execute();
$search_stmt->bind_result($product_id, $product_title);
etc...
The bind_param has to get the appropriate number of params since there will be more then one when two or more search criterias is used..
Thanks in advance.
EDIT:
This is the error message that i get:
“Number of elements in type definition string doesn’t match number of bind variables in..”
EDIT2:
echo $sql results in (with two criterias):
SELECT product_id, product_title FROM product WHERE product_title = ? AND product_categoryid = ?
echo $types results in :
ss
Which is correct aswell so the query is working as intended.
The thing is that $values will be one string, containing:
[searchCondition1][SearchCondition2]
for example: if i search on Volvo in the category Vehicles an echo $values will output Volvo2 where 2 is the categoryId.
But this is hardcoded and it is not a very good solution. The thing is, in your example, you call bind_param with
$types = 'ss';and$valuesis only 1 parameter ( doesn’t matter if it is like$values = 'one,two';, it is still 1 parameter.