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

报告相同问题?