如果已到达多个单元格,则为新行

时间:2011-09-03 03:44:13

标签: php mysql html-table

我正在尝试制作一个iframe表格(每行2个)并且我会查询所有内容,但无论何时打印,即使我只告诉每一秒钟,一切都在它自己的行上。我无法弄清楚为什么会这样:

<div id="main" style="width:1000px;">
    <?php
        $query = "SELECT * FROM scripts";
        mysql_connect("localhost", "root", "");
        mysql_select_db("scriptsearch");
        $results = mysql_query($query);
        $num = mysql_num_rows($results);
        mysql_close();
    ?>
    <table border="0">
    <?php
        for($i = 0; $i <= $num; $i++){          
        if($i % 2 == 0) //is this the second one? if so, make a new row
            echo '<tr>';
        else{
    ?>
    <td><iframe src="scriptpreview.php?id=<?php echo $i;?>" style="width: 350px; height: 230px;" frameBorder="0" scrolling="no">Your browser needs to support iFrames for this website.</iframe></td>
    <?php }if($i % 2 == 0) echo '</tr>';/*end the row*/ } ?>
    </table>
</div>`

编辑:我尝试过Krynble的解决方案,但无论我如何修改它,它仍然没有显示出我的期望。

4 个答案:

答案 0 :(得分:1)

循环中出现错误。

试试这个:

<?php
    for($i = 0; $i <= $num; $i++){          
    if($i % 2 == 0) //is this the second one? if so, make a new row
        echo '<tr>';
?>
<td><iframe src="scriptpreview.php?id=<?php echo $i;?>" style="width: 350px; height: 230px;" frameBorder="0" scrolling="no">Your browser needs to support iFrames for this website.</iframe></td>
<?php if($i % 2 == 1) echo '</tr>';/*end the row*/ } ?>
<?php if($i % 2 == 1) //close last row in case we haven't done it yet.
        echo '</tr>';?>

答案 1 :(得分:0)

你应该无条件地打印iframe,而不是在else中。此外,当</tr>为奇数时,应打印结束$i

答案 2 :(得分:0)

其他人评论了php / html部分,让我关注查询部分:

不要这样做:

$query = "SELECT * FROM scripts";          (1) select all ?
mysql_connect("localhost", "root", "");    (3) don't connect as root!
mysql_select_db("scriptsearch");
$results = mysql_query($query);            (4) no check for errors?
$num = mysql_num_rows($results);           (2) when you only want 1 count?

请改为:

$query = "SELECT count(*) as rowcount FROM scripts";                 
mysql_connect("localhost", "user1", "password");
mysql_select_db("scriptsearch");
if ($results = mysql_query($query)) {
  $row = mysql_fetch_row($results);
  $num = $row['rowcount'];
} else { echo "error....." }          

答案 3 :(得分:-1)

您的表格中没有开放<tr>标记。在将数据放入其中之前,您需要有一个表格行。

相关问题