duandi8613 2015-12-02 02:10 采纳率: 100%
浏览 82
已采纳

如何检查PHP中是否已存在postgres prepared语句

I have a PHP script that calls a function sometimes multiple times in one script run.

The function looks like this:

function insert_values($values) {
$sql = "insert into...";
pg_prepare($connection,"statement_name",$sql);
pg_execute($connection,"statement_name",array($values));
}

Everything is good so far - when it executes once

However, if my script calls this function more than once on that same connection, PHP gives a warning as:

[Tue Dec 01 20:58:31 2015] [error] [client 10.64.241.13] PHP Warning:  pg_prepare(): Query failed: ERROR:  prepared statement "insert_values" already exists in /var/www/include/classes/classes.php on line 955

Now, if this was just a a simple PHP warning, I might not pay attention to it.

However on the Postgres end, it states Query failed: ERROR - so of course the query does not run.

Obviously I understand why Postgres would kill somebody creating a NEW prepared statement with the same name on the same connection.

So.... does anybody know if there is a simple way to check if the prepared statement already exists and if it already exists, then just to take the already-created prepared statement?

Thank you.

  • 写回答

1条回答 默认 最新

  • dpbsy60000 2015-12-02 02:24
    关注

    One solution would be to use a static variable to indicate whether you have created the statement yet. The first time the function executes, $once is false, and it will prepare the statement and change $once to true. After that, it won't recreate the statement.

    function insert_values($values) {
        static $once = false;
        if ($once === false) {
            $sql = "insert into...";
            pg_prepare($connection,"statement_name",$sql);
            $once = true;
        }
        pg_execute($connection,"statement_name",array($values));
    }
    

    A static variable exists only in a local function scope, but it does not lose its value when program execution leaves this scope.

    From: http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵