This tutorial aims to guide you on how to retrieve data from a MySQL database and display it on your webpage. By the end of this tutorial, you will be able to create a simple webpage that fetches data from a MySQL database and displays it on the webpage dynamically.
Prerequisites:
The first step in retrieving data from a MySQL database is to establish a connection to the database. In PHP, this can be done using the mysqli_connect()
function.
Once a connection is established, you can fetch data from your database using SQL queries. In PHP, this can be done using the mysqli_query()
function.
After fetching the data, it can be displayed onto your webpage using HTML and CSS. Here, PHP is embedded within the HTML to dynamically display the fetched data.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
This script will try to connect to the database. If the connection is successful, it will print "Connected successfully". If the connection fails, it will print "Connection failed" along with the error message.
<?php
$sql = "SELECT id, firstname, lastname FROM MyGuests";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
This script first executes an SQL query that selects all data from the 'MyGuests' table. If the query returns any rows, it will loop through each row and print the data. If no rows are returned, it will print "0 results".
In this tutorial, we learned how to connect to a MySQL database, fetch data using SQL queries, and display the data on a webpage using HTML and CSS embedded with PHP.
Next, you could learn about data insertion and deletion from a database. You could also learn about securing your database connections and queries.
Remember to always close your database connections after you're done with them to free up resources. Happy coding!