How to bind N number of parameters using mysqli prepared statements?

后端 未结 1 1338
被撕碎了的回忆
被撕碎了的回忆 2021-01-28 06:39

In old mysql code, I had a query below which worked perfectly which is below:

$questioncontent = (isset($_GET[\'questioncontent\'])) ? $_GET[\'questioncontent\']         


        
相关标签:
1条回答
  • 2021-01-28 07:29

    Take a look at this SO Post that talks about the use of call_user_func_array with bind_param().

    From the PHP Docs on mysqli_stmt_bind_param it says the following...

    Note:

    Care must be taken when using mysqli_stmt_bind_param() in conjunction with call_user_func_array(). Note that mysqli_stmt_bind_param() requires parameters to be passed by reference, whereas call_user_func_array() can accept as a parameter a list of variables that can represent references or values.

    You'll want to use something like this

    call_user_func_array(array($stmt, 'bind_param'), $terms);
    

    and it's up to you to ensure that the correct number of ? characters appear in your SQL string $stmt.

    [EDIT]

    Here's a working example

    // user entered search strings
    $user_terms = array("a", "b", "c");
    
    // append your wildcard "%" to all elements. you must use "&" reference on &$value
    foreach ($user_terms as &$value) {
        $value = '%'.$value.'%';
    }
    
    $types = "";
    for($i = 0; $i<sizeof($user_terms); $i++) {
        $types .= "s";
    }
    
    $terms = array_merge( array($types), $user_terms);
    
    // the array $terms now contains: { "sss", "%a%", "%b%", "%c%" }
    
    $sql = "SELECT ... ?,?,?"    // edit your sql here
    
    $stmt = $mysqli->prepare($sql)
    
    call_user_func_array(array($stmt, 'bind_param'), $terms);
    
    0 讨论(0)
提交回复
热议问题