Steps in PHP Code for Querying a Database
In PHP, querying a database means sending an SQL query to the database (usually MySQL) and
getting the result.
1 Step 1: Connect PHP with the Database – Use mysqli_connect() to establish connection.
2 Step 2: Write the SQL Query – Create the SQL query such as SELECT * FROM students.
3 Step 3: Execute the Query – Run the query using mysqli_query().
4 Step 4: Fetch the Data – Retrieve results using mysqli_fetch_assoc().
5 Step 5: Close the Connection – Close the database using mysqli_close().
Full Example Program:
<?php
$conn = mysqli_connect("localhost", "root", "", "college");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM students";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row["id"] . " Name: " . $row["name"] . "<br>";
}
} else {
echo "No records found";
}
mysqli_close($conn);
?>