如何从PHP传递变量到MySQL存储过程

时间:2010-09-03 15:37:18

标签: php mysql stored-procedures sorting

我有以下存储过程:

proc_main:begin

declare done tinyint unsigned default 0;
declare dpth smallint unsigned default 0;


create temporary table hier(
 AGTREFERRER int unsigned, 
 AGTNO int unsigned, 
 depth smallint unsigned default 0
)engine = memory;

insert into hier values (p_agent_id, p_agent_id, dpth);

/* http://dev.mysql.com/doc/refman/5.0/en/temporary-table-problems.html */

create temporary table tmp engine=memory select * from hier;

while done <> 1 do

  if exists( select 1 from agents a inner join hier on a.AGTREFERRER = hier.AGTNO and hier.depth = dpth) then

    insert into hier 
      select a.AGTREFERRER, a.AGTNO, dpth + 1 from agents a
      inner join tmp on a.AGTREFERRER = tmp.AGTNO and tmp.depth = dpth;

    set dpth = dpth + 1;      

    truncate table tmp;
    insert into tmp select * from hier where depth = dpth;

  else
    set done = 1;
  end if;

end while;


select 
 a.AGTNO,
 a.AGTLNAME as agent_name,
 if(a.AGTNO = b.AGTNO, null, b.AGTNO) as AGTREFERRER,
 if(a.AGTNO = b.AGTNO, null, b.AGTLNAME) as parent_agent_name,
 hier.depth,
 a.AGTCOMMLVL
from 
 hier
inner join agents a on hier.AGTNO = a.AGTNO
inner join agents b on hier.AGTREFERRER = b.AGTNO
order by
 -- dont want to sort by depth but by commission instead - i think ??
 -- hier.depth, hier.agent_id; 
 a.AGTCOMMLVL desc;

drop temporary table if exists hier;
drop temporary table if exists tmp;

end proc_main

虽然该功能可以很好地工作 - 但它目前只允许通过AGTCOMMLVL降序进行排序。存储过程的目的是将memberID与其parentID和关联的COMMLVL进行匹配。一旦配对得当,我在第二个查询中使用memberID来返回有关该特定成员的信息。

我希望能够按任意数量的过滤器进行排序,但存在以下问题:

  1. 我似乎无法找到一种方法将变量传递给存储过程,以便按字段更改其排序。

  2. 即使我可以 - 排序实际上可能只包含来自第二个查询的数据(例如名字,姓氏等)

  3. 即使语法正确,在第二个查询中运行排序也不会执行任何操作 - 它总是会回退到存储过程的排序。

  4. 任何想法?

    修改

    我的php使用mysqli代码:

    $sql = sprintf("call agent_hier2(%d)", $agtid);
    $resulta = $mysqli->query($sql, MYSQLI_STORE_RESULT) or exit(mysqli_error($mysqli));
    

3 个答案:

答案 0 :(得分:2)

如果要按存储过程的输入参数排序,则需要使用Prepared staments 例如,

DELIMITER //
CREATE  PROCEDURE `test1`(IN field_name VARCHAR(40) )
BEGIN
  SET @qr = CONCAT ("SELECT * FROM table_name ORDER BY ",  field_name);

  PREPARE stmt FROM @qr;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END //

答案 1 :(得分:0)

$stmt = $dbh->prepare("CALL sp_takes_string_returns_string(?)");
$value = 'hello';
$stmt->bindParam(1, $value, PDO::PARAM_STR|PDO::PARAM_INPUT_OUTPUT, 4000); 

// call the stored procedure
$stmt->execute();

print "procedure returned $value\n";

答案 2 :(得分:0)

这也适用于Mysql 5.6

DELIMITER //
CREATE PROCEDURE `test1`(IN field_name VARCHAR(40) )
BEGIN
  "SELECT * FROM table_name ORDER BY ",  field_name);
END //