0

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
2
  • and how the generated html looks? Commented Jun 18, 2013 at 13:38
  • Look at the values of $cName and $cValue before you use str_replace(). Commented Jun 18, 2013 at 13:56

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.