PHP / PHP Database Integration

Retrieving and Displaying Data

Learn how to fetch data from your MySQL database and display it on your web page in this tutorial.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Introduces connecting PHP with databases using MySQL and PDO.

Introduction

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:

  • Basic knowledge of HTML & CSS
  • Basic understanding of PHP
  • MySQL database and basic SQL commands

Step-by-Step Guide

Database Connection

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.

Fetching Data

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.

Displaying Data

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.

Code Examples

Database Connection

<?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.

Fetching and Displaying Data

<?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".

Summary

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.

Practice Exercises

  1. Create a webpage that displays all the usernames from the 'Users' table in your database.
  2. Create a webpage that displays a user's full name and email when provided with a username.
  3. Create a webpage that displays all users ordered by their last login date.

Remember to always close your database connections after you're done with them to free up resources. Happy coding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Markdown to HTML Converter

Convert Markdown to clean HTML.

Use tool

URL Encoder/Decoder

Encode or decode URLs easily for web applications.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Lorem Ipsum Generator

Generate placeholder text for web design and mockups.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help