在PHP中嵌套while循环以从数据库获取数据

时间:2018-09-13 18:23:31

标签: php sql-server while-loop

<?php
$sqlquerypmenu = "select * 
                    from subsubmenu 
                    where submenu_id=1 
                    and position='left' 
                    and status=1";
if($querypmenu = sqlsrv_query($conn,$sqlquerypmenu)){
    if(sqlsrv_has_rows($querypmenu) === true){
        while($rowdata = sqlsrv_fetch_array($querypmenu, SQLSRV_FETCH_ASSOC)){
?>                            
<h4 class="title-small folder_name">  <?php echo $rowdata ['website_title'];   ?> </h4>
 <?php
            $id = $rowdata['id']; 
            $filequerymenu = "select * 
                                from upload_files 
                                where main_menu='value_name' 
                                and sub_menu='value_key' 
                                and subsub_menu= $id  ";  
            if($filemenu = sqlsrv_query($conn,$filequerymenu)){
                if(sqlsrv_has_rows($filemenu) === true){ 
                    while($filedata = sqlsrv_fetch_array($filemenu, SQLSRV_FETCH_ASSOC)){  ?>
<a class="smalltext font_val" href="<?php echo DOCUMENT_URL.$filedata ['file_name'];  ?> "  target="_blank"  ><?php echo $filedata['document_name']; ?></a> 
<?php
                    } 
                } 
            }     
        }
    }
}
?> 

在嵌套的 while循环中,第二个 while循环仅显示第一行数据,而不显示其余数据。

我该如何解决?

1 个答案:

答案 0 :(得分:0)

考虑通过一次JOIN查询来查询数据库一次。可能在while循环中打开另一个访存会导致实例问题:

<?php
...

$sql = "select s.website_title, u.file_name, u.document_name
        from upload_files u
        inner join subsubmenu s ON u.subsub_menu = s.id
        where u.main_menu = 'value_name' 
          and u.sub_menu = 'value_key'
          and s.submenu_id = 1 
          and s.[position] = 'left'
          and s.[status] = 1
        order by s.id, s.website_title;"

$title = "";

if($result = sqlsrv_query($conn, $sql)){
    if(sqlsrv_has_rows($result) === true){
        while($rowdata = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){

             if($title != $rowdata['website_title']) {
                  $title = $rowdata['website_title'] 
?>
               <h4 class="title-small folder_name">  <?php echo $rowdata ['website_title'];   ?> </h4>
<?php
             }
?>    
                    <a class="smalltext font_val" href="<?php echo DOCUMENT_URL.$filedata ['file_name'];  ?> "  target="_blank"  ><?php echo $filedata['document_name']; ?></a>
<?php
        }
    }        
}

?>