PHP for循环 - 在表格中显示数据

时间:2012-11-24 16:12:31

标签: php html mysql

我无法理解为什么我的代码无效;它只显示1个结果,而表中有多个条目。

<?php  

    $search = $_POST['search'];
    print ($search);
    $query  = "SELECT * FROM student WHERE county= 'sussex'";
    $result = mysql_query($query,$conn);
    $counter = 0;
    $z=0;
    while($row = mysql_fetch_assoc($result)){
    $id[$counter] = $row['roll_number'];
    $counter = $counter + 1;
    }
?>
<table border="1" id="table1" >
    <th>Id</th>
    <th>Type</th>
    <th>Description</th>
    <th>Operator Id</th>

<?
    if($counter>0)
    {
        for($z=0;$z<$counter;$z++)
        {
?> 
            <tr>
            <?
                if($z<$counter)
                {
            ?>
                <td >
                    <?php echo $id[$z]?>                            
                </td> 
            <?
                }
                $z = $z + 1;
            ?>   
            </tr>
</table>

1 个答案:

答案 0 :(得分:4)

你忘了关闭FOR循环及其封闭的IF,我已经在下面完成了它:

<?
if($counter>0)
{
    for($z=0;$z<$counter;$z++)
    {
?> 
        <tr>
            <?
                if($z<$counter)
                {
            ?>
                <td >
                    <?php echo $id[$z]?>                            
                </td> 
            <?
                }
                //$z = $z + 1;  <!-- REMOVE or comment out this line -->
            ?>   
            </tr>
     <? }
     }  ?> <!-- HERE we close the for loop and the IF -->
</table>

更新:感谢VinceBurn,$ z增加了两倍