2012-08-14 78 views
0

Hy。我知道有类似的答案,但我无法完成。这里是我的鳕鱼:在循环外显示变量

<?php include 'header.php'; ?> 
<?php include 'connect.php'; 

$q = mysqli_query($link, $aaa = 'SELECT * FROM agentii LEFT JOIN orase ON agentii.oras=orase.oras_id WHERE orase.oras_id = \'' .$_GET['id']. '\'') or die(mysqli_error($link)); 
$row = mysqli_fetch_assoc($q); 
?> 

<h2>Title <em><?php echo $row['oras'];?></em></h2> 

<div class="div_view"> 
    <table cellspacing="0" cellpadding="5" border="0" width="100%"> 
     <tr> 
      <th>Agentie</th> 
      <th>Adresa</th> 
     </tr> 

     <?php while ($row = mysqli_fetch_assoc($q)) { ?> 

     <tr> 
      <td><?php echo $row['agentie'];?></td> 
      <td><?php echo $row['adresa'];?></td> 
     </tr> 

     <?php }?> 

    </table> 
</div> 

<?php include 'footer.php'; ?> 

此输出(我不能把图像,因为是一个新的帐户 - 所以我把一个链接到一个PRT SRC): http://postimage.org/image/w9zsexz91/

在我的数据库,我有3个行和代码输出只有2. 我知道这是因为2 mysqli_fetch_assoc,但我想显示所有的行,并且我想在外面显示标题(<?php echo $row['oras'];?>)。

有人可以帮助我吗? Thx提前!

回答

1

强制性警告第一:切记小Bobby Tables! (或:你的代码很容易受到SQL注入攻击)

然后:你在while循环只有两行,因为你要求的行外循环首先,增加结果中的内部游标。

如果你想获得冠军和行一气呵成,你需要缓存的结果,例如:

$resultArray = array(); 
while ($row = mysqli_fetch_assoc($q)) { 
    $resultArray[] = $row; 
} 
//.... 
?> 
<h2><?php echo $resultArray[0]['oras']; ?></h2> 

<?php // ... ?> 

<?php foreach($resultArray as $row) { 
    <tr> 
    <td><?php echo $row['agentie'];?></td> 
    <td><?php echo $row['adresa'];?></td> 
    </tr> 
} ?> 

这只是一个存根,你当然应该执行检查,如果你有一排在所有等...

+0

是的!这工作。 Thx男人!两个答案都很好,但我会坚持你的答案 - 这对我来说更有意义。 – Luna84 2012-08-14 08:20:29

0

尝试:

<?php do { ?> 

<tr> 
    <td><?php echo $row['agentie'];?></td> 
    <td><?php echo $row['adresa'];?></td> 
</tr> 

<?php } while ($row = mysqli_fetch_assoc($q)); ?> 

这个循环的第一次迭代将打印第一读取行。我只更改了while子句的位置,强制循环的代码在获取新行之前运行。

+0

Thx人 - 为快速和良好的答案!有用! – Luna84 2012-08-14 07:53:01