My goal is pretty straightforward: I want to generate an HTML table with the headers showing the column names of a MySQL table and the body showing the contents of that MySQL table. I’m trying to make this as efficient as possible using loops – the headers were a piece of cake:
$columns = mysql_query("SHOW COLUMNS FROM my_table;");
while($row = mysql_fetch_array($columns)) {
echo '<th>'.$row['Field'].'</th>';
}
But I’m having trouble getting the body data, and was hoping someone could help. Here’s how I think this should work:
$query = mysql_query("SELECT * FROM my_table;");
while($row = mysql_fetch_array($query)) {
echo '<tr>';
foreach($row as $r) {
echo '<td>'.$r.'</td>';
}
echo '</tr>';
}
But the code above returns two instances of each value (value1, value1, value2, value2…), and I’m pretty sure that’s because each value in the array actually has two keys (the numerical one and the text one), so it’s printing each one twice. I can’t figure out how to get it to just print each field once. I also tried the code below instead of the foreach loop – this code actually prints each of the table’s 12 fields once, but then prints 12 empty td tags, again because it’s double counting the number of items in the array:
for($i =0; $i < count(array_keys($row)); $i++) {
echo '<td>'.$row[$i].'</td>';
}
Basically, I just need a function that returns the correct length of the array, preferably using a foreach loop but I’m open to a for lopp too – whatever works! Any ideas?
Just replace mysql_fetch_array with mysql_fetch_assoc or mysql_fetch_row.
Note that instead of doing a
SHOW COLUMNSquery, you can use mysql_field_name. You’d have to adapt your code a little, though.