I am trying to build a dynamic HTML table (regardless of number of columns or rows) from a MySQL query but I think I might be doing something wrong as it doesn't work at all.
I have experience with Oracle but I am new to MySQL. I have tried to check that the MySQL/PHP functions I am using do exist and I think that is the case.
<?php
$mysqli = new mysqli("localhost", "dbuser", "dbpass", "db");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT * FROM user")) {
/* build html table */
echo "<table class='table '><thread><tr>";
$ncols = mysqli_num_rows($result);
for ($i = 1; $i <= $ncols; $i++) {
$column_name = mysqli_field_name($result, $i);
echo "<th>".$column_name."</th>";
}
echo "</tr></thread><tbody>";
while ($row = mysqli_fetch_array($result, OCI_NUM)) {
echo "<tr>";
for ( $ii = 0; $ii < count($row); $ii++ ) {
echo "<td>" . $row[$ii] . "</td>";
}
echo "</tr>";
}
echo "</tbody></table>";
/* free result set */
$result->close();
}
$mysqli->close();
?>
Appreciating any help!
Steve
Edit: I added the error reporting as suggested and get:
Fatal error: Call to undefined function mysqli_field_name() in connection.php on line 20
mysqli_num_rowsdoesn't actually count columns of your table with the query you use...mysqli_field_countseems to be what you need...print_ron$result,$ncolsand then on$rowinside the loop. You will then see what data you have to play with and can work forward from that. Also adderror_reporting(E_ALL); ini_set('display_errors', 1);to the top of your document to display errors to the browser. Let us know what you get.