-2

My code is given below. In which I can only print the table headings. I want the table whose name I entered in the database should show the entire table.

<?php

$dataconn = mysqli_connect("localhost", "root", "", "databasename");
$sql = "SELECT * FROM employeedetails";
$res = mysqli_query($dataconn, $sql);
$show = mysqli_fetch_all($res, MYSQLI_ASSOC);
$col = $show[0];
$columns = array();

echo "<pre>";
foreach ($col as $key => $value) {
    if (is_string($key)) {
        $columns[] = $key;
    }
}
echo "<table border='1' cellpadding='10'>";
foreach ($columns as $value) {
    echo "<th>$value</th>";
}
for ($x = 0; $x < count($show); $x++) {
    echo "$value";
}
Dharman
  • 30,962
  • 25
  • 85
  • 135

2 Answers2

1

Your for loop does not iterate over the array with data. It is only displaying the same value N times.

Your approach to displaying HTML table with header is a little bit too complex. MySQLi has a special function called fetch_fields() that will give you metadata about the columns in the result. You can use that to display the header row.

echo '<table>';
    // Display table header
    echo '<thead>';
    echo '<tr>';
    foreach ($res->fetch_fields() as $column) {
        echo '<th>'.htmlspecialchars($column->name).'</th>';
    }
    echo '</tr>';
    echo '</thead>';

If the result set also contains actual data then you can iterate the array with data and display it row by row.

    $show = mysqli_fetch_all($res, MYSQLI_ASSOC);
    // If there is data then display each row
    if ($show) {
        foreach ($show as $row) {
            echo '<tr>';
            foreach ($row as $cell) {
                echo '<td>'.htmlspecialchars($cell).'</td>';
            }
            echo '</tr>';
        }
    }
echo '</table>';
Dharman
  • 30,962
  • 25
  • 85
  • 135
0

On second foreach loop you are printing same variable which you have used for column name, so its printing the column name also for second loop, edited code below please check, to print table data you need to print result of query

<?php

$dataconn = mysqli_connect("localhost", "root", "", "database");
$sql = "SELECT * FROM tablename";
$res = mysqli_query($dataconn, $sql);
$show = mysqli_fetch_all($res, MYSQLI_ASSOC);
$col = $show[0];
$columns = array();
echo "<pre>";
foreach ($col as $key => $value) {
    if (is_string($key)) {
        $columns[] = $key;
    }
}
echo "<table border='1' cellpadding='10'>";
echo "<tr>";
foreach ($columns as $value) {
    echo "<td>$value</td>";
}
echo "</tr>";

foreach ($show as $tableData) {
    echo "<tr>";
    foreach ($tableData as $key => $val) {
        echo "<td>$val</td>";
    }
    echo   "</tr>";
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
Tausif
  • 420
  • 2
  • 15