Retrieving data from the database

September 19, 2022

In the previous post, we learnt how we insert data into the database. In this post, let us learn how we can retrieve data from the database. Don’t worry, it is as simple as the previous operation. To retrieve data, we are going to use the mysqli_query function again. Let us create the retrieve.php page where our information will be retrieved to and write the logic for retrieving data.



    include 'connect.php';

    $sql = "SELECT visitor, feedback FROM feedback";
    $query = mysqli_query($connect, $sql);

    if (mysqli_num_rows($query) > 0) {
        while($row = mysqli_fetch_assoc($query)) {
            echo $row["visitor"] . " " . $row["feedback"] . "<br>";
    } else {
        echo "No records";



Let us break this code down. We started by including the connect.php in the retrieve.php file since it has the database connection codes we need. We proceeded to writing the SQL statement used to retrieve data from the database. You can visit this post to understand how it works but basically it gets data from the feedback table in columns visitor and feedback.

We proceeded by creating a query to store the mysqli_query function and its parameters (remember we used it in the previous post and we said it takes two arguments i.e. database connection and the SQL statement). We don’t have to necessarily create this variable but for easy readability of our code, we decide to create it.

We use an if statement to check if there are records in this table. If there are records (checked by mysqli_num_rows function using the database connection and the provided SQL) i.e. records are greater than zero meaning there are records, then we use a while loop to return all of them or else No records message will be returned.

In the while loop condition, we used the mysqli_fetch_assoc function that takes the database connection and retrieval SQL statement to return all records in the database. All these are stored in a variable called $row for readability. Inside the loop, we output the name of the visitor represented as $row[“visitor”] (which is the column name for visitor in the table) and feedback represented as $row[“feedback”] (which is the column name for feedback in the table).

Finally you see ” “, <br> and a dot. The dot is for joining the different string parts (see how to use string operators). Then the ” ” is to create a space between the visitor’s name and the feedback provided. The <br> is an HTML tag for breaking text to the next line. We used it because we need each record on a new line.

That is it 😘. Hope you learnt how to retrieve data from the database. You can go ahead and create simple projects as you continue to improve on your skills. I cannot wait to see some of your projects 🧑‍💻

Back To Top