Skip to content
Advertisement

How to turn a table vertical using PHP

I am just learning PHP ,and I want to create a table that display echo data that I submit to my database , the problem I have that the table displayed horizontally by default as you see Horizontal default table this my script

<table >
<tr>
<th>Name</th>
<th>Age</th>
<th>Height</th>
</tr>
<?php
$conn = mysqli_connect("localhost", "root", "", "class");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Name, Age, Height FROM student order by Name desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Name"]. "</td><td>" . $row["Age"] . "</td><td>"
. $row["Height"]. "</td></tr>";
}
echo "</table>";
} else //{ echo "0 results"; }//
$conn->close();
?>
</table>

but I want it to be echoed vertically instead like this VERTICAL RESULT I WANT and I tried to change html in echo in my PHP code but I can’t get the result at all and the shape of the table is far away from what I want and this is the full script of my page .

Advertisement

Answer

Like everyone else said, you should convert your horizontal array into a vertical one.

Of course it should be a universal function to convert any query result, as opposed to hardcoding the row headings. The idea is to get each row’s array keys and use them as the keys for the new array and then add each corresponding value to the new array item.

Here is how it’s done in mysqli:

<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect('127.0.0.1','root','','test');
$mysqli->query("set names 'UTF8'");

$data = [];
$res = $mysqli->query("SELECT Name, Age, Height FROM student order by Name desc");
while ($row = $res->fetch_assoc()) {
    foreach(array_keys($row) as $key) {
        $data[$key][] = $row[$key];
    }
}

and then you get an array with desired structure which you can output using the code from ROOT’s answer:

<table border="1">
  <?php foreach($data as $key => $val): ?>
    <tr>
      <td><?= $key ?></td>
      <?php foreach($val as $field): ?>
        <td><?= $field ?></td>
      <?php endforeach ?>
    </tr>
  <?php endforeach ?>
</table>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement