调用mysql PROCEDURE里面while循环只能第一次工作

时间:2013-08-09 11:07:47

标签: php mysql loops stored-procedures procedure

我有一些数据来自我发布在桌面上的数据库。对于表的每一行(while循环的每个循环),我需要调用一个存储过程来计算我表的最后<td>的数据。

这里有一些代码:

$s = $lk->query("SELECT *
                  FROM A_USERS
                  JOIN A_DATA
                  WHERE A_DATA.id_user = A_USERS.id
                    AND A_USERS.usr_att = 1
                    AND A_DATA.act_data = 1
                    AND A_DATA.a_att = 1
                    AND A_DATA.qty IS NOT NULL
                  ORDER BY ID ASC");


while ($dato = $s->fetch_object()) {
    print '<tr>';

    print '<td>';   
    print $dato->id;
    print '</td>';

    //others cells


    $GetP = $lk->query("CALL GetPr($dato->qty, '$dato->prod')");

    if(mysqli_num_rows($GetP) === 1){
        while($p_db = mysqli_fetch_array($GetP)){
            $p = $p_db['p'];
        }

        $format = number_format(round($p, 1), 2, ',', '\'');

        //some other stuff here...

    }else{
        print '<td>';
        print 'ERROR';
        print '</td>';
    }
    print '</tr>';
}

问题是只有while的第一个循环调用返回1 row的过程。另外,我ERROR总是<td>,这意味着存储过程没有返回1 row

为什么?

修改

存储过程:

CREATE DEFINER=`...` PROCEDURE `GetPr`(IN `cli_qty` INT, IN `cli_prod` VARCHAR(10) CHARSET ascii)
BEGIN
    SET @cli_qty = cli_qty;

    SET @q = (SELECT qty FROM MRG_H ORDER BY ABS(@cli_qty - qty) ASC LIMIT 1);

    SET @cli_prod = cli_prod;

    IF @cli_prod = 'OECO' THEN SET @marg = (SELECT (m+v) FROM MRG_H JOIN DT WHERE m <> '' AND q = @q AND par = 'MarOECO');

    ELSE SET @marg = (SELECT m FROM MRG_H WHERE m <> '' AND q = @q);
    END IF;

    SELECT (Med+@marg)*((Val+100)/100) AS P, D_aaaammgg AS Date
        FROM PL
          JOIN TVA
        WHERE I_D = 0
      AND Med <> ''
      AND Date_f = ''
        ORDER BY Iden DESC
        LIMIT 1;
END

MYSQLI错误:

Error: 2014-Commands out of sync; you can't run this command now

2 个答案:

答案 0 :(得分:2)

不确定这是不是问题,但是mysqli_fetch_array会使内部指针前进,而是用mysqli_num_rows替换它。

while($p_db = mysqli_fetch_array($GetP)){
        $p = $p_db['p'];
    }

编辑:

http://www.php.net/manual/en/mysqli.query.php#102904

$s->close();

$lk->next_result();

将此2放在//其他单元格下。

而且,ty用fetch_all替换fetch_object。

答案 1 :(得分:2)

根据@Mihai的建议,我找到了这个解决方案:

参考:PHP Manual

while ($dato = $s->fetch_object()) {
    print '<tr>';

    print '<td>';   
    print $dato->id;
    print '</td>';

    //others cells


    $GetP = $lk->query("CALL GetPr($dato->qty, '$dato->prod')");

    if(mysqli_num_rows($GetP) === 1){
        while($p_db = mysqli_fetch_array($GetP)){
            $p = $p_db['p'];
        }

        $format = number_format(round($p, 1), 2, ',', '\'');

        //some other stuff here...

    }else{
        print '<td>';
        print 'ERROR';
        print '</td>';
    }

    //Added this 2 lines
    $GetPrice->close();
    $link->next_result();

    print '</tr>';
}