How to display data from mysql database into html table using php code example
Example 1: how to display data from mysql database into html table using php
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Example 2: mysql data to html table
<?php
$host = "localhost";
$user = "username_here";
$pass = "password_here";
$db_name = "database_name_here";
$connection = mysqli_connect($host, $user, $pass, $db_name);
if(mysqli_connect_errno()){
die("connection failed: "
. mysqli_connect_error()
. " (" . mysqli_connect_errno()
. ")");
}
$result = mysqli_query($connection,"SELECT * FROM products");
$all_property = array();
echo '<table class="data-table">
<tr class="data-heading">';
while ($property = mysqli_fetch_field($result)) {
echo '<td>' . $property->name . '</td>';
array_push($all_property, $property->name);
}
echo '</tr>';
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
foreach ($all_property as $item) {
echo '<td>' . $row[$item] . '</td>';
}
echo '</tr>';
}
echo "</table>";
?>