php - 从 PHP 将 MySQL 结果输出为 <table> 格式的正确方法是什么?

标签 php mysql

当输出到<table>时如何显示你的MySQL结果?格式?我觉得我自己的代码可以使用一些编辑。我这样做是否正确?

编辑:我的代码显然是错误的/难看的。在仅使用纯 PHP 而不是 Smarty 的情况下执行此操作的最佳方法是什么?

$items_per_row = 3; // How many <td> I want to add for every <tr>

// Query the MySQL db
$sthandler = $dbhandler->prepare("SELECT col1, col2 FROM sampletable");
$sthandler->execute();

// Save each row to array
$allitems = array();
while($row = $sthandler->fetch(PDO::FETCH_ASSOC)){
    $allitems[] = $row;
}

$markup = '';
foreach($allitems as $key=>$val){
    $col1 = $allitems[$key]['col1'];
    $col2 = $allitems[$key]['col2'];

    // START THE MARKUP HERE
    $markup .= $key % $items_per_row == 0 ? '<tr>' : '';
    $markup .= <<<EOD
    <td>
        <p>$col1</p>
        <p>$col2</p>
    </td>
EOD;
    $markup .= ($key + 1) % $items_per_row == 0 ? '</tr>' : '';
}

然后我可以<table><?php echo $markup; ?></table> .

最佳答案

将您的业务逻辑与您的表示代码分开!!!

我使用模板解析器将 HTML 与 PHP 分开。例如,使用 Smarty我会使用类似的东西:

// Sample data
$tableData = array(
    array('col1', 'col2'),
    array('col1', 'col2'),
    array('col1', 'col2'),
    array('col1', 'col2'),
);

// Create the view
$tpl = new Smarty();
$tpl -> assign('table', $tableData);
$tpl -> display('myPage.tpl');

然后在模板文件中我建表:

<table>
{foreach from=$table item=row}
    <tr>
        <td>{$row.0|escape}</td>
        <td>{$row.1|escape}</td>
    </tr>
{/foreach}
</table>

这将您的 HTML 与 PHP 代码分开,使添加新功能更容易,并使您的代码更具可读性。

编辑
糟糕,你真的需要把你的问题改那么大吗?

好吧,改用这个模板:

<table>
<?php foreach ($tableData as $row) { ?>
    <tr>
        <td><?php echo htmlspecialchars($row[0]); ?></td>
        <td><?php echo htmlspecialchars($row[1]); ?></td>
    </tr>
<?php } ?>
</table>

用法:

// Sample data
$tableData = array(
    array('col1', 'col2'),
    array('col1', 'col2'),
    array('col1', 'col2'),
    array('col1', 'col2'),
);

// Create the view
include('myPage.php');

当然,这个解决方案比使用适当的模板引擎要脏得多。

关于php - 从 PHP 将 MySQL 结果输出为 <table> 格式的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8690023/

相关文章:

php - 为什么在 MySQL 中使用 SUM() 时会得到重复的值?

php - Ajax 成功 jquery php

MySQL 不区分大小写的字符串匹配使用 =

php - 将多页 PDF 文件拆分为单页

php - 从公钥散列到 php 中的比特币地址

php - Mac OS X Apache 安装无法正常工作 403 Forbidden

PHP 负载测试框架

php - 如何从 mysql 中显示一个 PHP 变量的所有结果?

mysql - 无法计算正确的总小时数?

php - PHP没有错误,但是数据库中没有条目?