To fetch the existing data from the database we first need to establish the database connection. If you didn't know how to establish the database connection , you can visit this article ⇨PHP database connection
To fetch the existing data from the database we need to learn the query that how to write the fetch query, and we will use the two PHP mysqli functions.
1- mysqli_query() 2- mysqli_fetch_assoc()SELECT * FROM table_name
We use the ' * ' to fetch all columns from the table , however we can fetch one or more columns also.
SELECT first_name,last_name FROM table_name
We can also write the WHERE condition in the fetch query.
SELECT * FROM table_name WHERE id=1
Now we are going to fetch the user's data from the below users table that contains two users record.
Note ! For fetching more than one record we will use the while loop , if we didn't use while loop than only one record will display.
<?php
$conn = mysqli_connect('localhost', 'root', '', 'myfirstdatabase');
$sql_query = mysqli_query($conn,"SELECT * FROM users");
$fetch_result = mysqli_fetch_assoc($sql_query);
echo $fetch_result['first_name'];
echo $fetch_result['last_name'];
?>
Output: HussainKhan
This above fetch function only displayed one user's first-name and last-name 'HussainKhan ' . If we want to display the number of records we will use the while loop like below.
<?php
$conn = mysqli_connect('localhost', 'root', '', 'myfirstdatabase');
$sql_query = mysqli_query($conn,"SELECT * FROM users");
while($fetch_result = mysqli_fetch_assoc($sql_query))
{
echo $fetch_result['first_name'];
echo $fetch_result['last_name'];
echo "<br>"; //<br> is using to place a line break after one record fetch.
}
?>
Output:
HussainKhan
UmerKhan