从php调用存储的postgres函数

时间:2010-03-29 10:23:58

标签: php postgresql function

我最初在这里发布了这个问题:How do I fetch a stored postgres function from php

我接受了答案,但是,它实际上对我不起作用......这是最初的问题:

我在postgres中有一个函数,当我在pg提示符时,我只是这样做:

SELECT zp('zc',10,20,90);
FETCH ALL FROM zc;

我想知道如何从php做到这一点?

我以为我可以做:

$q = pg_query("SELECT zp('zc',10,20,90)");

但是,如何从该查询中“获取”?

我还不完全确定如何做到这一点......

我试过

$q = pg_query("SELECT zp('zc',10,20,90)");
$f = pg_query("FETCH ALL FROM zc");
while($row = pg_fetch_array($f)) ... 

while($row = pg_fetch_all($f)) ...

$q = pg_query("SELECT zp('zc',10,20,90);FETCH ALL FROM zc;")
while($frow = pg_fetch_array($q)) ... 

1 个答案:

答案 0 :(得分:1)

这有效:

创建一个返回CURSOR的函数:

CREATE FUNCTION myfunc(refcursor) RETURNS SETOF refcursor AS $$
BEGIN
    OPEN $1 FOR SELECT * FROM tbl_name;
    RETURN NEXT $1;
END;
$$ LANGUAGE plpgsql;

而不是PHP代码:

<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
$con = pg_connect('host=localhost port=5432 user=**** password=**** dbname=****');

pg_query($con, "BEGIN;");
pg_query($con, "SELECT * FROM myfunc('a');");

$result = pg_query($con, "FETCH ALL FROM a;");

echo '<pre>';
print_r(pg_fetch_all($result));
echo '</pre>';

pg_query($con, "COMMIT;");
?>

如果您有任何问题,您有什么问题?有错误吗?