【问题标题】:Newbie, while loops新手,while循环
【发布时间】:2009-07-12 02:00:54
【问题描述】:

标题

$id = intval($_GET['id']);
$query = mysql_query("SELECT * FROM table WHERE id = $id");

查看

while ($row = mysql_fetch_array($query)) {
 $column1 = $row['column1'];
 $column2 = $row['column2'];
 $column3 = $row['column3'];

 echo $column1.......
}

如何将上述代码保留在我的头文件中?
所以我的设计师就不用看了吗?

能否将数据保存到变量中并在页面上打印出来?

谢谢!

【问题讨论】:

    标签: php


    【解决方案1】:

    您可以使用MVC pattern 将逻辑与演示分开。

    最简单的方法是将您想要呈现的所有数据保存到局部变量或数组中,然后需要一个视图文件。

    视图文件只是在 html 模板中回显数据。

    如果您想更深入地挖掘,可以查看 codeignitercakephp 之类的框架。

    【讨论】:

      【解决方案2】:

      您可以创建一个函数,该函数将 $GET_['id'] 值作为参数并返回应回显的任何内容。

      类似:(inc.php)

      <?php
      function queryCall($id)
      {
          $query = mysql_query("SELECT * FROM table WHERE id = $id");
          $ret = "";
          while ($row = mysql_fetch_array($query)) {
              $column1 = $row['column1'];
              $column2 = $row['column2'];
              $column3 = $row['column3'];
      
              $ret .= $column1.......
          }
          return $ret;
      }
      ?>
      

      然后在你的主文件中:

      <?php include 'inc.php'; ?>
      
      ...
      
      <?php
      echo queryCall(intval($_GET['id']));
      ?>
      ...
      

      【讨论】:

        【解决方案3】:

        我建议你 intval() 内联 ID,这样就可以清楚地知道查询不会受到 SQL 注入的影响。

        将所有代码放入名为header.php 的文件中。使用循环创建一个数组()。调用数组,比如$Rows

        然后在您的主 html 文件 (.php) 中输入:

        <?php include('header.php'); ?>
        <html>
           <head>...</head>
           <body>
              <table>
                  <?php foreach($Rows as $row) { ?>
                     <tr>
                        <td><?php echo htmlspecialchars($row['column1']); ?></td>
                        <td><?php echo htmlspecialchars($row['column2']); ?></td>
                        <td><?php echo htmlspecialchars($row['column3']); ?></td>
                     </tr>
                  <?php } ?>
              </table>
           </body>
        </html>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-01-03
          • 1970-01-01
          • 2011-10-13
          • 1970-01-01
          • 2016-04-24
          • 1970-01-01
          • 1970-01-01
          • 2015-01-04
          相关资源
          最近更新 更多