Reputation: 63
I want my database data to be shown in a table. I have the following code but it just paste everything next to each other.
CODE:
<?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;
?>
and in my HTML file I have:
<table>
%%header%%
%%data%%
</table>
The result I get is:
IDAlbumBandStijlMediumDatumPrijsIDAlbumBandStijlMediumDatumPrijs
1TestTestereRockLP2013-06-1202TestTestereRockLP2013-06-1213
but I want it to be like:
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
Upvotes: 0
Views: 144
Reputation: 5390
while($row = mysql_fetch_assoc($result))
{
foreach($row as $columnName=>$columnValue)
{
$cName .= $columnName;
$cValue .= $columnValue;
}
}
needs to be
$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>";
}
this is a modified version of functions provided in the comments of the (mysql_fetch_assoc function)[http://www.php.net/manual/en/function.mysql-fetch-assoc.php] and
$template = str_replace("%%header%%", "<tr><th>". $cName ."</tr></th>", $template);
$template = str_replace("%%data%%", "<tr><td>". $cValue ."</tr></td>", $template);
needs to be
$template = str_replace("%%header%%", "<tr>". $cName ."</tr>", $template);
$template = str_replace("%%data%%", "<tr>". $cValue ."</tr>", $template);
This is because each coloumn needs a seperate td or th tag.
Upvotes: 3