使用mysqli绑定未知数量的参数 [英] Binding an unknown number of parameters using mysqli

查看:75
本文介绍了使用mysqli绑定未知数量的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在表格中进行搜索,例如: http://www.phpjabbers.com/free-scripts/mysql-search-table/search.php

I'm trying to make a search in a table, something like this: http://www.phpjabbers.com/free-scripts/mysql-search-table/search.php

我发现我可以根据搜索表单$ _GET来连接一个字符串,这样我就可以在获取参数后查询所有字符串:

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']);

我正在遵循这篇文章的说明: https://stackoverflow.com/a/11152781/679333 ,但是通配符部分无效.当我将变量推入数组时,我引用了这些变量,而不是for循环:

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.

我不想忽略该警告,因为我阅读了调用时传递引用已被PHP杀死.

I don't want to ignore the warning because I read Call-time pass-by-reference has now been killed from PHP.

推荐答案

有点草率,但是可以完成工作.

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));

应该这样做,尽管我以前从未绑定过mysqli.让我知道它是如何工作的.

That should do it, though I've never bound with mysqli before. Let me know how that works.

这篇关于使用mysqli绑定未知数量的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆