首页 > 解决方案 > 函数错误中的 MySQL 调用过程

问题描述

我正在尝试从程序结果中获取计数。我已经看到您可以创建一个临时表并稍后对其进行计数。但是当我将我的过程添加到函数中时,它停止工作。这是为什么?

  $connection->query('
   drop procedure if exists parents;
   create procedure parents(in parent int(11),in name varchar(22))
   begin
    set @parent=parent;
    drop temporary table if exists ids;
    create temporary table ids(id int(11));
    while @parent<>0 do
     prepare statement from concat("select related into @parent from ",name," where id=?");
     execute statement using @parent;
     insert into ids(id) values(@parent);
    end while;
    select*from ids;
   end;
   drop function if exists counted;
   create function counted(parent int(11),name varchar(22))
   returns int(11)
   begin
    call parents(parent,name);
    return (select count(*) from ids);
   end;
   ');
   $fetch=$connection->query('select counted(3,"category");')->fetchall();

我收到一个获取布尔错误。

标签: phpmysqlstored-proceduresmysqli

解决方案


您不能在一次调用中执行多个查询query()(您可以使用 来执行此操作multi_query(),但您不能自定义查询分隔符以区分;分隔查询和过程中使用的查询)。因此,将其分为多个查询。

  $connection->query('xdrop procedure if exists parents');
  $connection->query('
   create procedure parents(in parent int(11),in name varchar(22))
   begin
    set @parent=parent;
    drop temporary table if exists ids;
    create temporary table ids(id int(11));
    while @parent<>0 do
     prepare statement from concat("select related into @parent from ",name," where id=?");
     execute statement using @parent;
     insert into ids(id) values(@parent);
    end while;
    select*from ids;
   end;
  ');
  $connection->query('drop function if exists counted');
  $connection->query('
   create function counted(parent int(11),name varchar(22))
   returns int(11)
   begin
    call parents(parent,name);
    return (select count(*) from ids);
   end;
   ');
   $fetch=$connection->query('select counted(3,"category");')->fetchall();

推荐阅读