dongya6381 2016-04-27 14:40
浏览 92

SQL中的while循环只循环一次

I have a rest service where I send a get request to a table in my database. I want to build an array with the response. I get the array-structure I want with this code but the problem is that it only loops once. Why is this? If I change the second $result to $result2 it returns false instead of the encoded array.

/**
 * @param int $id
 * @url periodicalitem
 * @return string
 */
public function getPeriodicalItem($id){

    $mysqli = $this->db-> getConnection();

    $query  = 'SELECT * FROM periodicalitem WHERE
        periodical_id  = ' . $id;

    $result = $mysqli->query($query);
    $arr = array();

    while ($row = $result->fetch_assoc()) {

        $query = 'SELECT * FROM inst_codes WHERE id = ' . $row['inst_code'] . '';
        $result = $mysqli->query($query);


        while ($row2 = $result->fetch_assoc()) {

            if($row['inst_code'] == $row2['id'] ){
                $arr[$row2['id']] = array('name' => $row2['name'],
                                          'data' => $arr[$row2['id']]['data'] ? array_push($arr[$row2['id']]['data'], $row) : array($row) );

            }
        }

    } 

    return json_encode($arr); 

}
  • 写回答

2条回答 默认 最新

  • duanpai6581 2016-04-27 14:41
    关注

    You are over-writing $result = $mysqli->query($query); inside the loop. Use another variable

    public function getPeriodicalItem($id){
    
        $mysqli = $this->db-> getConnection();
    
        $query  = 'SELECT * FROM periodicalitem WHERE
            periodical_id  = ' . $id;
    
        $result = $mysqli->query($query);
        $arr = array();
    
        while ($row = $result->fetch_assoc()) {
    
            $query = 'SELECT * FROM inst_codes WHERE id = ' . $row['inst_code'] . '';
            $result1 = $mysqli->query($query);
    
    
            while ($row2 = $result1->fetch_assoc()) {
    
                if($row['inst_code'] == $row2['id'] ){
                    $arr[$row2['id']] = array('name' => $row2['name'],
                                              'data' => $arr[$row2['id']]['data'] ? array_push($arr[$row2['id']]['data'], $row) : array($row) );
    
                }
            }
    
        } 
    
        return json_encode($arr); 
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题