Page 1 of 1

How to parse this db to HTML?

Posted: Wed Mar 10, 2010 8:51 pm
by Bimyoo
I'm noob!

How do I put a db like this:

Code: Select all

 CREATE TABLE `scores` (
  `date` date NOT NULL,
  `diet` tinyint(4) NOT NULL,
  `study` tinyint(4) NOT NULL,
  `exercise` tinyint(4) NOT NULL,
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
 
-- 
-- Dumping data for table `scores`
-- 
 
INSERT INTO `scores` VALUES ('2010-03-01', 10, 20, 5);
INSERT INTO `scores` VALUES ('2010-03-02', 5, 10, 20);
 
into HTML like this:

Code: Select all

<table>
    <thead>
        <tr>
            <td></td>
            <th>2010-03-01</th>
            <th>2010-03-02</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th>Diet</th>
            <td>10</td>
            <td>5</td>
        </tr>
        <tr>
            <th>Study</th>
            <td>20</td>
            <td>10</td>
        </tr>
        <tr>
            <th>Exercise</th>
            <td>5</td>
            <td>20</td>
        </tr>
    </tbody>
</table>
 
with PHP kind of like this:

Code: Select all

<?php
include("config.php");
$table="scores"; // Table name
 
// sending query
$result = mysql_query("SELECT date FROM {$table}");
    if (!$result) { die("die!");}
 
echo "<table>";
echo "<thead><tr><td></td>";
// printing table headers
while($row = mysql_fetch_row($result)){
    // $row is array... foreach( .. ) puts every element
    // of $row to $cell variable
     foreach($row as $cell)
        echo "<th>$cell</th>";
}
echo "</tr></thead>";
echo "<tbody>";
 
//new group
$result = mysql_query("SELECT diet, study, exercise FROM {$table}");
    if (!$result) { die("die!");}
 
for($i=0; $i<3; $i++){
        echo "<tr>";
        $field = mysql_fetch_field($result);
        echo "<th>{$field->name}</th>";
            while($row = mysql_fetch_row($result))
            {
                echo "<td>".$row[$i]."</td>";
            }
        echo "</tr>";
}
echo"</tbody></table>";
mysql_free_result($result);
?>
 
I know that's messy, but it's the closest I've gotten...