简体   繁体   中英

PHP, PDO binding dynamic number of values into the statement

I need effective some solution for the following issue: For some reason that would be too much time-consuming to explain properly, I need a PDO prepare statemnt sorta looking this way:

'SELECT field, another field, blabla FROM table WHERE some_foreign_id = first_val AND the_same_foreign_id = second_val AND again_the_same_id = third val ......' 

and Id wish to fill the values with an array of unknown size, that depends on how many fields in that foreign table fits to a certain category in yet another table. So the querstion is: is it even possible or should I give it up and find some naive walkaround?

Thanks in advance! Mac

You can pass an array of values into stmt ->execute($array); The only tricky part would be getting the number of question marks to enter.

    $foreign_ids = array(foreign_id_1, foreign_id_2, foreign_id_3); //etc
    $input_list = substr(str_repeat(',?', count($foreign_ids)), 1);  //this gets you the correct number of ? to use for your query
    // if you need add another value to the parameters you can use array_push($foreign_ids,$your_other_param);


    $stmt= $dbh->prepare("
        SELECT field, another_field
        WHERE some_foreign_id = ($input_list)");
    $stmt->execute($foreign_ids);

It should be possible. You'll need to generate your query dynamically with question marks for parameters, and then bind with an array at the point of execution.

See example 3 on the PDO::execute page of the PHP docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM