I am pretty new to PHP and just spent several hours watching video and wrote first PHP code. I meet one problem with display PHP fetch data to frontend html table.
Below is my database, code, and frontend page.
This is my database field and data
This is my PHP code
<?php
$conn=mysqli_connect("localhost","root","123456","links");
$sql="SELECT * FROM `countries` WHERE `continent`='Asia'";
$result =$conn->query($sql);
echo '<h2 align="center">List of Countries in Asia</h2>';
echo '<table align="center" width="800px" border="1" cellspacing="0" cellpadding="1"><tr align="center"><td colspan="4">Asia</td><tr>';
echo '<tr><th>id</th><th>code</th><th>Country Name</th><th>Continent</th></tr>';
while($row = mysqli_fetch_array($result))
{
echo
"<tr align='center'><td>{$row['id']}</td> ".
"<td>{$row['code']} </td> ".
"<td>{$row['name']} </td> ".
"<td>{$row['continent']} </td> ".
"</tr>";
}
echo '</table>';
Now I just want to show countries field in the table, no need other fields, I don’t know how to achieve it, I made a html page and this is just what I want to show.
This is what I want to achieve
Is there anyone who can help me and point the roadmap and logic to achieve it, thanks in advance.
I tried hours but still can not get this one, I want to show only one field database data and show in one row and then anther row.
2
Answers
You only want to show the country names. In that case you can remove the other fields. The only real problem is when to start a new row.
You can solve this problem by counting how many country names you’ve put in the table, with a
$counter
. Initialize the$counter
to zero, since you’ve not added any country when you start. Then, every time you echo a country name, you increase the value of$counter
by one.Then for the real tricky bit: Every time five countries have been displayed you need to start a new row. I do this with the modulo operator:
$counter % 5
. The remainder of$counter
divided by five will be zero when$counter
is a whole multiple of five.This results in the code below.
I cannot test this code, because I don’t have your database, but I think it should work.
This solution still works with a table, like in your code. A more modern approach would be to use a grid-layout, as suggested by shingo in a comment.
You can use this kind of logic as well. In the below code block you can append empty table data elements. You can also set $table_width variable based on your need.