Problem with HTML tables - PHP/MySQL
Posted: Sat Jul 12, 2008 9:14 pm
Hi everybody, this is my first post here. It is also the first code I write so excuse me if it is messy and basic, but like a first child it made me so proud...
I wanted to create a function that would generate an HTML table from any MySQL table. The following code works (works!) very well. I have tried to add columns and records to the MySQL table and it works.
The only problem is that the FIRST record of the MySQL table is not shown in the HTML table, it starts from the second record. Why?
It would be great if you can help me.
phest
I wanted to create a function that would generate an HTML table from any MySQL table. The following code works (works!) very well. I have tried to add columns and records to the MySQL table and it works.
The only problem is that the FIRST record of the MySQL table is not shown in the HTML table, it starts from the second record. Why?
It would be great if you can help me.
phest
Code: Select all
<?php
$link = mysqli_connect('localhost', 'root', 'whatever', 'whatever');
$select = "select * from customers";
$result = mysqli_query($link, $select);
$result_data = mysqli_fetch_assoc($result);
reset($result_data);
$i = 0;
$my_table[0] = ($result_data);
while ($result_data = mysqli_fetch_assoc($result)){
$my_table[$i] = ($result_data);
++$i;
}
//automatically generates a table from any bidimensional array
function create_table($array)
{
if((is_array($array[0])) == true) //checks if $array is multidimensional, if not it exits
{
echo "<table>\n";
echo "\t<tr>\n";
$first_row = $array[0];
foreach ($first_row as $col_name => $data) // highlights the first row of the table
{
echo "\t\t<td class=\"firstrow\">$col_name</td>\n";
}
echo "\t</tr>\n";
reset($array); // beginning of array
$row = current($array); //gets current data - row
reset($row);
while ($row) //loop as long as there is a row
{
$cell = current($row); //gets current data - column
echo "\t<tr>\n";
while ($cell) //loop as long as there is a column
{
echo "\t\t<td>$cell</td>\n";
$cell = next($row);
}
echo "\t</tr>\n";
$row = next($array);
}
echo "</table>\n";
}
else
{
echo "<h1>no table</h1>"; // just to check
exit;
}
}
create_table($my_table);
mysqli_close($link);
?>