如何通过1个php / mysql结果循环多次

时间:2013-03-05 02:33:38

标签: php mysql

想知道是否有更简单的方法来做这件事......

我有一个包含大量行的表,需要根据名为“page_group”的1列上的特定值单独显示它们。现在它确实有效,当我将结果的指针重置为零,但想知道是否有更简单的代码方式,因为至少有15个不同的部分来分组结果......?

//this is the query
$q_home = mysql_query("SELECT * FROM pages WHERE page_nav = 'No' ORDER BY page_group ASC");

//this would show results 1, showing all rows that have the value "sample1"
<h3>Result 1</h3>
<ul>
<? 
    while($r_nav = mysql_fetch_assoc($q_home)){
      $group_folder = $r_nav['page_group'];
      if ($r_access["$group_folder"] == "Yes" && $group_folder == 'sample1') { 
            $access = 'block;'; 
        } else { 
            $access = 'none;'; 
        } {;
            echo '<li style="display:'.$access.'"><a href="'.$group_folder.'/'.$r_nav['page_url'].'.php">'.$r_nav['page_name'].'</a></li>';
      }
    }
?>
</ul>   

//this would be result 2 showing all rows that have value "sample2"
<h3>Result 2</h3>
<ul>
<? 
    mysql_data_seek($q_home, 0);
   while($r_nav2 = mysql_fetch_assoc($q_home)){
      $group_folder = $r_nav2['page_group'];
      if ($r_access["$group_folder"] == "Yes" && $group_folder == 'sample2') { 
            $access = 'block;'; 
        } else { 
            $access = 'none;'; 
        } {;
            echo '<li style="display:'.$access.'"><a href="'.$group_folder.'/'.$r_nav2['page_url'].'.php">'.$r_nav2['page_name'].'</a></li>';
      }
    }
?>
</ul>

2 个答案:

答案 0 :(得分:0)

你在循环中有mysql_fetch,所以不要在特定的$group_folder上停止循环(删除if子句的那一部分):

<ul>
<?php
  while($r_nav = mysql_fetch_assoc($q_home)){
    $group_folder = $r_nav['page_group'];
    if ($r_access["$group_folder"] == "Yes")
      $access = 'block;';
    else
      $access = 'none;';
    echo '<li style="display:'.$access.'">
    <a href="'.$group_folder.'/'.$r_nav['page_url'].'.php">
    '.$r_nav['page_name'].'</a></li>';
  }
?>
</ul>   

答案 1 :(得分:0)

这样的循环将是更好的解决方案:

$q_home = mysql_query("SELECT * FROM pages WHERE page_nav = 'No' ORDER BY page_group ASC");
$x = 1;
<? while( $r_nav = mysql_fetch_assoc($q_home) ) { ?>
<h3>Result <?= $x; ?></h3>
<ul>
<?php
  $group_folder = $r_nav['page_group'];
  if( $r_access["$group_folder"] == "Yes" && $group_folder == 'sample1') {
    $access = 'block;';
  }
  else { 
    $access = 'none;';
  }
  echo '<li style="display:'.$access.'"><a href="'.$group_folder.'/'.$r_nav['page_url'].'.php">'.$r_nav['page_name'].'</a></li>';
  }
  $x++;
?>
</ul>
<?php } ?>