2015-12-02 02:10
浏览 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...";

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

图片转代码服务由CSDN问答提供 功能建议

我有一个PHP脚本,在一次脚本运行中有时多次调用一个函数。 \ n


  function insert_values($ values){
 $ sql =“insert into ...”; 
 npg_prepare($ connection,  “statement_name”,$ sql); 
pg_execute($ connection,“statement_name”,array($ values)); 

到目前为止一切都很好 - 当它执行一次


 <  code> [Tue Dec 01 20:58:31 2015] [error] [client] PHP警告:pg_prepare():查询失败:错误:准备好的语句“insert_values”已存在于/ var / www / include / classes中 第955行上的/classes.php 

现在,如果这只是一个简单的PHP警告,我可能不会注意它。 \ n

但是在Postgres端,它声明 Query failed:ERROR - 所以当然查询不会运行。


所以....有没有人知道 有一种简单的方法来检查 if 准备好的语句是否已经存在,如果它已经存在,那么只是采取已经创建的预准备语句?

谢谢 。

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

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...";
            $once = true;

    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

    解决 无用
    打赏 举报

相关推荐 更多相似问题