Display Data using PHP & MySQL Database
Introduction
Displaying data from a MySQL database is a key feature of most web applications. This guide explains how to fetch and present data dynamically using core PHP. It also incorporates SEO best practices to ensure your content ranks well on search engines.
Prerequisites
- Basic understanding of PHP and MySQL.
- A MySQL database with a table containing data to display.
- A web server (e.g., XAMPP, WAMP, or a live server) to execute PHP scripts.
Steps to Display Data from MySQL
1. Create a Database and Table
Run the following SQL commands to create a database and a table with sample data:
CREATE DATABASE demo_db; USE demo_db; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL, email VARCHAR(100) NOT NULL, age INT NOT NULL ); INSERT INTO users (name, email, age) VALUES ('John Doe', 'john.doe@example.com', 25), ('Jane Smith', 'jane.smith@example.com', 30);
2. Establish a Database Connection in PHP
Create a db_connection.php
file to handle the database connection:
<?php // Database connection settings $host = 'localhost'; $user = 'root'; $password = ''; // Use your database password $database = 'demo_db'; // Create connection $conn = new mysqli($host, $user, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>
3. Fetch and Display Data in PHP
Create a file named display.php
to fetch and display the data:
<?php // Include the database connection file include 'db_connection.php'; // Fetch all records from the users table $sql = "SELECT * FROM users"; $result = $conn->query($sql); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Display Users</title> <meta name="description" content="Learn how to display data from a MySQL database using PHP with this practical guide."> </head> <body> <h2>User List</h2> <table border="1"> <tr> <th>ID</th> <th>Name</th> <th>Email</th> <th>Age</th> </tr> <?php if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { ?> <tr> <td><?php echo $row['id']; ?></td> <td><?php echo $row['name']; ?></td> <td><?php echo $row['email']; ?></td> <td><?php echo $row['age']; ?></td> </tr> <?php } } else { echo "<tr><td colspan='4'>No records found.</td></tr>"; } ?> </table> </body> </html>
4. Run the Script
- Start your local server.
- Open the
display.php
file in your browser. - Verify that the data from the
users
table is displayed in a tabular format.
0 Replies to “Display Data Using PHP & Mysql Database”
Leave a Reply
Your email address will not be published.