Formatting Database Output in PHP
You already know how to retrieve data from the database. Let's now output this data, formatting it with tags.
For example, let's output the records from our test table users
in the following form:
<p>
<b>user1</b>
<b>23</b>
<b>400</b>
</p>
<p>
<b>user2</b>
<b>24</b>
<b>500</b>
</p>
<p>
<b>user3</b>
<b>25</b>
<b>600</b>
</p>
First, let's get an array of records from our database:
<?php
$query = "SELECT * FROM users";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
for ($data = []; $row = mysqli_fetch_assoc($result); $data[] = $row);
?>
Let's now output the data from our array in a formatted form:
<?php
$result = '';
foreach ($data as $elem) {
$result .= '<p>';
$result .= '<b>' . $elem['name'] . '</b>';
$result .= '<b>' . $elem['age'] . '</b>';
$result .= '<b>' . $elem['salary'] . '</b>';
$result .= '</p>';
}
echo $result;
?>
It can also be rewritten in the following form:
<?php foreach ($data as $elem): ?>
<p>
<b><?= $elem['name'] ?></b>
<b><?= $elem['age'] ?></b>
<b><?= $elem['salary'] ?></b>
</p>
<?php endforeach; ?>
Output the records from our table in the following form:
<div>
<h2>user1</h2>
<p>
23 years, <b>400$</b>
</p>
</div>
<div>
<h2>user2</h2>
<p>
24 years, <b>500$</b>
</p>
</div>
<div>
<h2>user3</h2>
<p>
25 years, <b>600$</b>
</p>
</div>
Output the records from our table in the following form:
<table>
<tr>
<th>id</th>
<th>name</th>
<th>age</th>
<th>salary</th>
</tr>
<tr>
<td>1</td>
<td>user1</td>
<td>23</td>
<td>400</td>
</tr>
<tr>
<td>2</td>
<td>user2</td>
<td>25</td>
<td>500</td>
</tr>
<tr>
<td>3</td>
<td>user3</td>
<td>23</td>
<td>500</td>
</tr>
</table>
Output the records from our table in the following form:
<ul>
<li>user1</li>
<li>user2</li>
<li>user3</li>
</ul>