gpt4 book ai didi

php - 如果我从 MySQL 中提取数据,是否必须使用 PHP 编写 HTML?

转载 作者:行者123 更新时间:2023-11-29 05:18:29 25 4
gpt4 key购买 nike

所以我能够从 MYSQL 中提取数据并遍历它并填充一个 <table>使用 html 标签在浏览器中呈现。我还有一个单独的 CSS 文件,用于设置 <table> 的样式。对我来说。

我的问题是,包含表格的网页的其余部分是否必须从同一个 PHP 文件和/或使用 PHP 构建?请问有人可以建议吗?

到目前为止,我的代码填充表格和创建网页是这样的:

  // Creating and populating table for 'filename' and 'title'.
echo '<link rel="stylesheet" type="text/css" href="css/main.css"/>';
echo '<table>';
echo "<tr><td class='tableHeader' colspan=2>List of Articles</td></tr>";
echo '<tr> <th>Filename</th> <th>Title</th> </tr>';

while($row = $result -> fetch_assoc()){
// Fetch result row as an associative array or NULL if there are no more rows.
$filename = $row['filename'];
$title = $row['title'];

echo "<tr> <td class='filename'>".$filename."</td> <td class='title'>".$title."</td></tr>";


}//end of while loop


echo '</table>';

最佳答案

编码需要了解以下内容HTMLPHP文件(必须以 .php 扩展名命名,以便服务器解析 PHP)。

PHP 总是被 <?php 包围和 ?> (对于后者并不总是如此,我们会回来的)。这意味着您可以:

<table>
<?php foreach($array as $key => $el) { ?>
<tr>
<td><?php echo $key;?></td>
<td><?php echo $el;?></td>
</tr>
<?php } ?>
</table>

那样的话,当你开始使用这些控制结构时,你应该使用the alternative ones .这对于理解代码结构更好。在做大量 HTML 时养成将 PHP 代码写成一行的习惯。

您还可以设置变量并按照此规则进行任意数量的治疗。

<section>
<?php for($i = 1; $i < 50; $i++): ?> <!-- note the alternative syntax -->
<?php $class = 'myClass-'.$i; ?>
<div class="<?php echo $class;?>">
<span>This is div #<?php echo $i;?></span>
</div>
<?php endfor;?>
</section>

这是为了让您习惯使用 Twig 或 Smarty 等模板引擎。

最后,您会看到许多未以 ?> 结尾的完整 PHP 文件.即prevent headers to be sent如果在其他文件中使用 PHP 进行 header 操作之前包含文件,以防结束标记后有空格。

关于php - 如果我从 MySQL 中提取数据,是否必须使用 PHP 编写 HTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29375176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com