Reputation: 455
I'm trying to make a search in a table, something like this: http://www.phpjabbers.com/free-scripts/mysql-search-table/search.php
I figured out that I could just concatenate a string depending on the search form $_GET so I can query it all after getting the parameters:
$query = "SELECT * FROM table WHERE status = 1"
if($_GET['param1']{
$query = $query." AND param1 = ?";
}
$stmt = $mysqli->prepare($query);
That would be perfect if I wouldn't have to add:
$stmt->bind_param('i',$_GET['art']);
I was following this post's instructions: https://stackoverflow.com/a/11152781/679333, but the wildcard part didn't work. Instead of that for loop I referenced the variables when I pushed them into the array:
array_push($user_terms, &$_GET['var']);
It works, but now I'm getting a "Deprecated: Call-time pass-by-reference has been deprecated" warning.
I don't want to ignore the warning because I read Call-time pass-by-reference has now been killed from PHP.
Upvotes: 2
Views: 1539
Reputation: 5740
A bit sloppy, but gets the job done.
function refValues($arr){
if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
{
$refs = array();
foreach($arr as $key => $value)
$refs[$key] = &$arr[$key];
return $refs;
}
return $arr;
}
$params = array();
$query = "SELECT * FROM table WHERE status = 1";
// Iterate over your paramters from $_GET
foreach ($_GET as $k => $v)
{
if(!empty($v)
{
$query .= " AND $k = ?";
$params[$k] = helper::sanitize($v);
}
}
// After you get through all your params...
$stmt = $mysqli->prepare($query);
// Bind em.
call_user_func_array(array($stmt, 'bind_param'), refValues($params));
That should do it, though I've never bound with mysqli before. Let me know how that works.
Upvotes: 3