What we are using here:
MySQL database:
–MySQL Username: root
–No MySQL Password
–Database Name: PracticeDatabase
–Table Name: Contacts
And 3 echo statements to print the HTML table.
The code:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php //Connect to the host. $con = mysql_connect('localhost','root','') or die(mysql_error()); //Connect to database. mysql_select_db('PracticeDatabase',$con) or die(mysql_error()); $result = mysql_query("select * from Contacts")or die(mysql_error()); //Print the table column names echo '<table border="1"> <tr> <th>Name</th> <th>Phone</th> </tr>'; //Print all the data from our database while($data = mysql_fetch_array($result)){ echo "<tr> <td>".$data['Name']."</td> <td>".$data['Phone']."</td> </tr> <br>"; } echo '</table> '; //End table tag. ?> |
Output:

Have a better way of doing this? Let us know and we will update it here.
A more versatile method would be to automatically fetch the field names, so you could create a reusable function that will return the data for any table:
function dbTableToHtml($table,$db){
$query=mysql_query(‘explain
'.$table.'‘,$db);$cols=array();
while($row=mysql_fetch_assoc($query)){
$cols[]=$row['Field'];
}
echo ”;
foreach ($cols as $col){
echo ”.$col.”;
}
echo ”;
$query=mysql_query(‘select * from `’.$table.”,$db);
while ($row=mysql_fetch_assoc($query)){
echo ”;
foreach ($cols as $col){
echo ”.$row[$col].”;
}
echo ”;
}
echo ”;
}
Oh. The comment function here removes all html. That kinda messed up my code.