dt4320279 2013-07-03 14:11
浏览 66
已采纳

php - plpgsql调用存储过程并获取结果集

I am trying to make a stored procedure which returns rows from the user table. I call it from php with pg_ functions: pg_prepare($conn, $id, 'SELECT user_read_all()') and pg_execute($conn, $id, array()). Sadly I don't have PDO just for mysql.

I tried with this code, but I have multiple problems:

CREATE OR REPLACE FUNCTION user_read_all()
  RETURNS table(user_id INT, user_name VARCHAR, user_email VARCHAR)
AS
  $BODY$
  BEGIN
    return query SELECT
      user_id, user_name, user_email
    FROM
      user;
  END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;

By pg_fetch, the result is array('test' => string(...)) instead of array(user_id => 1, user_name => '', user_email => ''). I want to cut off the user_ prefix too, but I got syntax error by this:

CREATE OR REPLACE FUNCTION user_read_all()
  RETURNS table(id INT, name VARCHAR, email VARCHAR)
AS
  $BODY$
  BEGIN
    return query SELECT
      user_id as id, user_name as name, user_email as email
    FROM
      user;
  END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;

;-(

Is it possible to do this with plpgsql?

My goal is to make a stored procedure only interface, but I have serious doubts... With mysql this is very easy, but mysql has limited functions only compared to pgsql...

CREATE PROCEDURE `user_read_all`()
BEGIN
    SELECT `user_id` AS `id`, `user_name` AS `name`, `user_email` AS `email` FROM `user`
    ORDER BY `user_id` DESC;
END;

So the question is how to fix the stored procedure and the php result set?

solution

CREATE FUNCTION test ()
  RETURNS TABLE (id INT, name VARCHAR, email VARCHAR)
AS
  $BODY$
  BEGIN
    return QUERY SELECT
      "user".user_id, "user".user_name, "user".user_email
    FROM
      "user";
  END;
$BODY$
LANGUAGE 'plpgsql' VOLATILE;

and

SELECT * FROM test();

on php side.

  • 写回答

3条回答 默认 最新

  • dpfwhb7470 2013-07-03 14:49
    关注

    It's a function returning a table, so you have to treat it like a table:

    SELECT * FROM user_read_all();
    

    Try both in psql and look carefully at the output. Your original way returns a set of row-types, the FROM way returns columns.

    Regarding the syntax error - you don't give it, so I can't say.

    Do avoid using reserved words for column/table-names though. Things like "type", "name", "user" etc. - see docs for details.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?