首页 > 解决方案 > 如何在php的while循环中执行mysql查询

问题描述

我的 mysql 连接有问题,我想在 mysqli_fetch_assoc 的一段时间内执行查询,但是,我收到类似“命令不同步;您现在无法运行此命令”之类的错误。

<?php
    $sql = "call sp_getUpline('$user_id')";
    $result = mysqli_query($connection,$sql);
    $numrow = mysqli_num_rows($result); 

    if($numrow > 1)
    {
        while($resultArray = mysqli_fetch_assoc($result))
        {
            $parent_id = $resultArray['parent_id'];
            if($parent_id != null)
            {
                $Level = $resultArray['Level'] + 1; 

                $comp_sql = "SELECT * FROM user_comp_plan where id='$parent_id'";
                $comp_result = mysqli_query($connection, $comp_sql) or die(mysqli_error($connection)); //getting error here

          }

        }
    }

?>  

更新

我将结果存储在数组中,但仍然遇到同样的问题。

<?php
        $sql = "call sp_getUpline('$user_id')";
        $result = mysqli_query($connection,$sql);
        echo $numrow = mysqli_num_rows($result);    

        if($numrow > 1)
        {
            $data = array();
            while($resultArray = mysqli_fetch_assoc($result))
            {
                $data[] = $resultArray;
            }
            for($i = 0; $i < count($data); $i++){       
                $parent_id = $data[$i]['parent_id'];
                if($parent_id != null)
                {
                    $Level = $data[$i]['Level'] + 1; 

                    $comp_sql = "SELECT * FROM user_comp_plan where id='$parent_id'";
                    $comp_result = mysqli_query($connection, $comp_sql) or die(mysqli_error($connection)); //getting error here

                }

            }
        }
?>

标签: phpmysql

解决方案


您不能同时进行两个查询,因为 mysqli 默认使用无缓冲查询。您可以将第一个获取到数组中并循环遍历,或者告诉 mysqli 使用 mysqli::store_result 缓冲查询


推荐阅读