douyu9159 2015-07-31 13:28
浏览 194
已采纳

如何使用IN()参数执行PostgreSQL PREPARE查询

I'm trying to prepare a query from PHP like:

pg_prepare($con, "prep", "select * from test where tid in ($1)");

and then execute it with:

$strpar = "3,4,6,8,10";
pg_execute($con, "prep", array($strpars));

The problem is that I cannot pass a series of values built as prepare expects a fixed number of parameters. Is there any way to make the parameters dynamic?

  • 写回答

1条回答 默认 最新

  • douyong5476 2015-07-31 13:31
    关注

    Use an array to represent the series of values:

    pg_prepare($con, "prep", "select * from test where tid=ANY($1)");
    
    $strpar = "{3,4,6,8,10}";
    pg_execute($con, "prep", array($strpars));
    

    You can also create a PHP function to receive a PHP array and set it as a valid array for a Postgres prepared statement as in:

    function php_array_to_pg ($array) {
    
        $values = "";
    
        foreach ($array as $value) {
            if ($values=="") {
            $values = $value;
            } else {
            $values = $values.",".$value;
            }
        }
    
        return "{".$values."}";
    }
    

    Then you make a statement such as:

    pg_prepare($con, "prep", "select * from test where tid=ANY($1)");
    
    $array = array(1,2,3,4);
    
    pg_execute($con, "prep", array(php_array_to_pg ($array)));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?