php - 这个过程会计算行数吗?我如何从 php 调用这个过程?

标签 php mysql

test1 是对传递两个变量 v_col1 和 v_col2 后创建的表的行进行计数的过程。当我在 MySQL 上运行它时,它显示

“MySQL 返回了一个空结果集(即零行)。(查询花费了 0.0020 秒)”

但是我无法从 php.ini 调用它。

 Delimiter $$
create procedure test1()
BEGIN
BLOCK1: begin
declare v_col1 int(10);                     
declare no_more_rows1 boolean default FALSE;  
declare cursor1 cursor for              
select content_id
from   topic_list where topic_id=1;
declare continue handler for not found  
set no_more_rows1 = TRUE;           
open cursor1;
LOOP1: loop
fetch cursor1
into  v_col1;
if no_more_rows1 then
close cursor1;
leave LOOP1;
end if;
BLOCK2: begin
  declare v_col2 int(10);
  declare no_more_rows2 boolean default FALSE;
  declare cursor2 cursor for
    select content_id
    from   content_upvotes
    where  u_id_upvoter = 1;
  declare continue handler for not found
   set no_more_rows2 = TRUE;
  open cursor2;
  LOOP2: loop
    fetch cursor2
    into  v_col2;
    if no_more_rows2 then
        close cursor2;
        leave LOOP2;
    end if;
    select count(*) as mynum from (SELECT *from content_upvotes where content_id=v_col1) t1 join (select u_id_upvoter as user_id from content_upvotes where content_id= v_col2) t2 on t1.u_id_upvoter=t2.user_id ;
  end loop LOOP2;
  end BLOCK2;
  end loop LOOP1;
  end BLOCK1;
  end $$
  DELIMITER ;

请帮帮我。

最佳答案

首先,观察结果(这不是您提出的问题的答案)...

对于它应该完成的任务来说,这个过程似乎过于复杂。

<小时/>

问:这个过程会计算行数吗?

答:如果您询问此过程是否会返回“行数”...

它将有条件地执行,条件是 cursor1 返回至少一行,并且 cursor2 在过程执行期间的某个时刻返回至少一行。回答你的第一个问题...

是的,mynum(过程的输出参数)可能会填充“行数”。

返回的“计数”将来自select count(*)查询的最后执行(位于loop2的底部)。任何先前执行 select count(*) 查询的结果都将被丢弃。

如果 cursor1 不返回行,则答案为,该过程不会返回任何“行数”。此外,如果 cursor2 从未返回一行,那么答案也是

<小时/>

问:如何从 PHP 调用此过程?

答:假设您正在使用 PDO,则可以使用如下模式:

<?php
$sth = $dbh->prepare("CALL test1(?)");
$sth->bindParam(1, $return_val, PDO::PARAM_INT, 20);
$sth->execute();

print "call to msyql stored procedure test1 returned $return_val\n";
?>
<小时/>

为了跟进我最初的观察...我对这个程序存在的任何充分理由感到困惑。

<小时/>

跟进

上面的代码示例解决了具有 OUT 参数的原始过程定义。问题中的过程定义已更改为删除 OUT 参数,并且 SELECT ... INTO var SQL 语句已更改为删除 INTO var 。修改后的过程有可能返回零个、一个或多个结果集。

要执行过程(不带参数)并从过程中检索所有结果集,您可以使用如下模式:

 <?php
 $sth = $dbh->prepare("CALL test1()");
 $sth->execute();

 $results = array();
 do {
    $rowset = $sth->fetchAll();
    if($rowset) {
       $results [] = $rowset;
    }
 } while ($sth->nextRowset());

 ?>

关于php - 这个过程会计算行数吗?我如何从 php 调用这个过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34816018/

相关文章:

mysql - 使用 Sequelize JS 插入唯一记录的更好方法

MySql - 当存在重复键时增加列

php - 如何在 woocommerce 中获得免费送货的最低订购量

php - 如果用户不是管理员,如何使菜单选项卡不可见

php - 将 TLS v1.2 用于 Amazon AWS 上的 Curl

php - 解锁的论坛帖子说已锁定?

php - 从同一个表中获取不同条件的数据

php - 您如何获取 Facebook 用户的信息并将其插入数据库?

php - 如何在MySQL中表示由产品组成的产品?嵌套集还是其他什么?

java - 指定驱动程序和连接详细信息中缺少 Eclipse MySQL 驱动程序