0

我希望我的数据库数据显示在表格中。我有以下代码,但它只是将所有内容粘贴在一起。

代码:

<?php
include ("core/db_connectie.php");

$template = file_get_contents("main.tpl.php");

$query = "SELECT * FROM platen";
$result = mysql_query($query) or die (mysql_error());

$cName = "";
$cValue = "";

while($row = mysql_fetch_assoc($result))
{   
    foreach($row as $columnName=>$columnValue)
    {
        $cName .= $columnName;
        $cValue .= $columnValue; 
    }
}

$template = str_replace("%%header%%", "<tr><th>". $cName ."</tr></th>", $template);
$template = str_replace("%%data%%", "<tr><td>". $cValue ."</tr></td>", $template);

echo $template;

?>

在我的 HTML 文件中,我有:

<table>
   %%header%%
   %%data%%
</table>

我得到的结果是:

IDAlbumBandStijlMediumDatumPrijsIDAlbumBandStijlMediumDatumPrijs
1TestTestereRockLP2013-06-1202TestTestereRockLP2013-06-1213

但我希望它像:

ID Album Band Stijl Medium Datum         Prijs
1  Test  Test Rock  LP     2013-06-1202  €10
2  Test  Test Rock  LP     2013-06-1202  €10
4

1 回答 1

3
while($row = mysql_fetch_assoc($result))
{   
    foreach($row as $columnName=>$columnValue)
    {
        $cName .= $columnName;
        $cValue .= $columnValue; 
    }
}

需要是

$i=0;
$values = array();
while ($row = mysql_fetch_assoc($result)) {
    foreach ($row as $key => $value) {
        $values[$key][$i] = $value;
    }
    $i++;
}
reset($arr);
foreach(current($arr) as $key => $value){
   $cName .= "<th>" . $key . "</th>";  
}  
while ($curr_row = current($arr)) {
    $cValue .= "<tr>";
    while (false !== ($curr_field = current($curr_row))) {
        $cValue .= "<td>" . $columnValue . "</td>"; 
        next($curr_row);
    }
    next($arr);
    $cValue .= "<\tr>";
} 

这是(mysql_fetch_assoc 函数)[http://www.php.net/manual/en/function.mysql-fetch-assoc.php] 和

$template = str_replace("%%header%%", "<tr><th>". $cName ."</tr></th>", $template);
$template = str_replace("%%data%%", "<tr><td>". $cValue ."</tr></td>", $template);

需要是

$template = str_replace("%%header%%", "<tr>". $cName ."</tr>", $template);
$template = str_replace("%%data%%", "<tr>". $cValue ."</tr>", $template);

这是因为每个列都需要一个单独的 td 或 th 标签。

于 2013-06-18T14:26:25.383 回答