dqsot35145 2013-01-10 22:31
浏览 83
已采纳

PHP / MySQL:使用预处理语句在WHERE子句中使用数组元素

I want to make a "dynamic" WHERE clause in my query based on a array of strings. And I want to run the created query using Mysqi's prepared statements.

My code so far, PHP:

$searchArray = explode(' ', $search);
$searchNumber = count($searchArray);
$searchStr = "tags.tag LIKE ? ";
for($i=1; $i<=$searchNumber-1 ;$i++){
    $searchStr .= "OR tags.tag LIKE ? ";
}

My query:

SELECT tag FROM tags WHERE $searchStr;

More PHP:

$stmt -> bind_param(str_repeat('s', count($searchArray)));

Now this obviously gives me an error since the bind_param part only contains half the details it need.

How should I proceed?

Are there any other (better) way of doing this?

Is it secure?

  • 写回答

3条回答 默认 最新

  • doushang4274 2013-01-11 20:09
    关注

    Solved it by the help of an answer found here.

    $query = "SELECT * FROM tags WHERE tags.tag LIKE CONCAT('%',?,'%')" . str_repeat(" OR tags.tag LIKE CONCAT('%',?,'%')", $searchNumber - 1)
    
    $stmt = $mysqli -> prepare($query);
    $bind_names[] = str_repeat('s', $searchNumber);
    
    for ($i = 0; $i < count($searchArray); $i++){
       $bind_name = 'bind'.$i; //generate a name for variable bind1, bind2, bind3...
       $$bind_name = $searchArray[$i]; //create a variable with this name and put value in it
       $bind_names[] = & $$bind_name; //put a link to this variable in array
    }
    
    call_user_func_array(array($stmt, 'bind_param'), &$bind_names);
    
    $stmt -> execute();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料