MySQLi prepared statements with IN operator

前端 未结 1 1813
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 23:53

I have to select some rows from the database using IN operator. I want to do it using prepared statement. This is my code:



        
相关标签:
1条回答
  • 2020-12-04 00:10

    I've recently found the solution for my question. Maybe it's not the best way to do it, but it works nice! Prove me wrong:)

    <?php
    $lastnames = array('braun', 'piorkowski', 'mason', 'nash');
    $arParams = array();
    
    foreach($lastnames as $key => $value) //recreate an array with parameters explicitly passing every parameter by reference
        $arParams[] = &$lastnames[$key];
    
    $count_params = count($arParams);
    
    $int = str_repeat('i',$count_params); //add type for each variable (i,d,s,b); you can also determine type of the variable automatically (is_int, is_float, is_string) in loop, but i don't need it
    array_unshift($arParams,$int); 
    
    $q = array_fill(0,$count_params,'?'); //form string of question marks for statement
    $params = implode(',',$q);
    
    $data_res = $_DB->prepare('SELECT `id`, `name`, `age` FROM `users` WHERE `lastname` IN ('.$params.')');
    call_user_func_array(array($data_res, 'bind_param'), $arParams);
    $data_res->execute();
    $result = $data_res->get_result();
    while ($data = $result->fetch_array(MYSQLI_ASSOC)) {
        ...
    }
    
    $result->free();
    $data_res->close();
    ?>
    
    0 讨论(0)
提交回复
热议问题