【问题标题】:PHP, PDO binding dynamic number of values into the statementPHP、PDO绑定动态数量值到语句中
【发布时间】:2012-09-24 21:21:36
【问题描述】:

我需要一些有效的解决方案来解决以下问题: 出于某种原因,正确解释太费时间了,我需要一个 PDO 准备语句,看起来像这样:

'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 ......' 

并且我希望用未知大小的数组填充值,这取决于该外部表中有多少字段适合另一个表中的某个类别。 所以问题是:是否有可能或者我应该放弃它并找到一些幼稚的解决方法?

提前致谢! 马克

【问题讨论】:

    标签: php arrays dynamic pdo bind


    【解决方案1】:

    你可以将一个值数组传递给 stmt ->execute($array);唯一棘手的部分是输入要输入的问号数量。

        $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);
    

    【讨论】:

      【解决方案2】:

      应该是可以的。您需要使用参数的问号动态生成查询,然后在执行时与数组绑定。

      请参阅 PHP 文档的 PDO::execute 页面上的示例 3

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-13
        • 2011-03-23
        • 1970-01-01
        • 2020-04-11
        • 2018-08-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多