Skip to main content

Practical-18

Write a PHP program for connection with my Sql and display all record from the database.

Meta Description

Write a PHP program for connection to a SQL database and displaying all records from the database with efficient coding.

Introduction

Are you looking for a step-by-step guide on how to write a PHP program for connection to a SQL database and displaying all records from the database? 🤔 This guide provides beginner-friendly coding techniques to establish a connection with a SQL database and displaying all records from the database in an efficient manner. 🤩 It is important to maintain the connection with the database in order to ensure the security of the data. Although this guide is written with beginners in mind, it can be used by those with more experience in programming. Following the steps laid out in this guide will help you to establish a successful connection with a SQL database and display all the records from the database. 🤓

Code

<?php
$HostName = "localhost";
$HostUser = "root";
$HostPass = "";
$DatabaseName = "database_name";

// Establishing the connection with the database server
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

// Checking for connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Running query on the database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Display all records from the database
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "id: " . $row["id"]. " - Name: " . $row["name"]. "<br>";
}
} else {
echo "0 results";
}

// Close the connection
$conn->close();
?>

Output

id: 1 - Name: John
id: 2 - Name: Jane
id: 3 - Name: Jack
id: 4 - Name: Jill
Explanation

This code establishes a connection with a SQL database and then runs a query to extract all records from a table. The code then loops through each record and displays the associated data in each row.

Get Help