Display data from SQL database with MySQLi into php - html table
OK, you have a database on phpmyadmin (sql) and you want to display one of table into a table on HTML PHP.
Select Data With MySQLi and display - how to create - example
In the following example selects the id, name and surname columns from the users table and displays it on the page:
<?php
$servername = "localhost";
$username = "your-username";
$pass = "your-password";
$dbname = "my-DB";
// Create connection
$link = new mysqli($servername, $username, $pass, $dbname);
// Check connection
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
echo "<table>";
$sql = "SELECT id, name, surname FROM Users order by rand() limit 4";
$result = $link->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["id"]. "
</td><td>"
". $row["name"]. "</td><td> " . $row["surname"]. "
</td></tr>
";
}
} else {
echo "0 results";
}
$conn->close();
?>
function - num_rows() - checks if there are more than zero rows returned.
If there are more than zero rows returned, the function -fetch_assoc() - puts all the results into an associative array that we can loop through. The - while() loop - loops through the result set and outputs the data from the id, name and surname columns.
MySQLi procedural way: Example - How to create
The following example shows the same as the example above, in the MySQLi procedural way:
<?php
$servername = "localhost";
$username = "your-username";
$pass = "your-password";
$dbname = "my-DB";
// Create connection
$link = mysqli_connect($servername, $username, $pass, $dbname);
// Check connection
if (!$link) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<table>";
$sql = "SELECT id, name, surname FROM Users order by rand() limit 4";
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>" . $row["id"]. "
</td><td>"
". $row["name"]. "</td><td> " . $row["surname"]. "
</td></tr>
";
}
} else {
echo "0 results";
}
$conn->close();
?>
The results -
Display data from SQL, database with MySQLi, php html table
Display data from SQL database with MySQLi into php - html table - sql tutorial
This tool makes it easy to create, adjust, and experiment with custom colors for the web.

Magnews2 is a modern and creative free magazine and news website template that will help you kick off your online project in style.

Find here examples of creative and unique website layouts.

Find here examples of creative and unique website CSS HTML menu.