【问题标题】:New row if a number of cells have been reached如果已达到多个单元格,则为新行
【发布时间】:2018-06-25 02:31:19
【问题描述】:

我正在尝试制作一个 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 的解决方案,但无论我如何修改它,它仍然没有达到我的预期。

【问题讨论】:

  • 你看过输出的html了吗?我想它看起来不像你期望的那样。
  • 理想情况下,您应该尽可能减少请求数量,因此如果您可以在没有 iframe 的情况下执行此操作,那就太好了。 :)

标签: php mysql html-table


【解决方案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>';?>

【讨论】:

    【解决方案2】:

    您应该无条件地打印 iframe,而不是在 else 中。此外,$i 为奇数时,应打印结尾的&lt;/tr&gt;。

    【讨论】:

      【解决方案3】:

      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....." }          
      

      【讨论】:

      • 感谢您的输入,我只是以 root 身份连接,因为我刚开始使用 WAMP,这是本地开发。一旦我真正上传它,我肯定会修复安全漏洞。
      【解决方案4】:

      您的表中没有打开的&lt;tr&gt; 标记。您需要有一个表格行才能将数据放入其中。

      【讨论】:

      • 第一个 if 语句在第一次执行时为真,因此有一个打开的&lt;tr&gt; 标签。
      猜你喜欢
      • 2013-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 1970-01-01
      • 2019-06-18
      • 2022-01-16
      • 1970-01-01
      相关资源
      最近更新 更多