MySQLI binding params using call_user_func_array

后端 未结 7 2324
别跟我提以往
别跟我提以往 2020-11-30 09:01

Please see below my code. I am attempting to bind an array of paramenters to my prepared statement. I\'ve been looking around on the web and can see I have to use call_user_

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 09:53

    Wasn't able to answer this on my own question because it got marked as dupe: here. But I think my final solution, which uses the answers in this question, works in my use case, might be helpful for someone.

    My goals was to take a posted set of ID's and use them in a NOT IN MYSQL statement. Assuming array of 5 ID's posted.

    1. Count the number posted ID's to build the ? placeholders for NOT IN statement. Using $params_count = substr(str_repeat(',?', count($array_of_ids)), 1); gives the result: (?,?,?,?,?) to be used in SQL statement.

    2. Make function that takes ID's and type i or s etc. For me, they were all i so my function is simpler. return array that looks like this $params= array("iiiii",1,2,3,4,5) where the first value is the set of i's and the subsequent values are the ID's depending on total ID's passed into function.

      function build_bind_params($values, $bind_type) {
          $s = substr(str_repeat($bind_type, count($values)), 0);
          $bind_array = array();
          $bind_array[] = $s;
          foreach($values as $value) {
              $bind_array[] = $value;
          }
          return $bind_array; 
      }
      

    $params = build_bind_params($array_of_ids, "i");

    1. Then use foreach ($params as $key => $value) $tmp[$key] = &$params[$key]; to get the newly created $params formatted properly for binding.

    2. Then use call_user_func_array(array($stmt , 'bind_param') , $tmp); to properly bind the array.

    3. Then execute the $stmt

提交回复
热议问题