Tutorial: Displaying Patient Data from a MySQL Database using PHP

By Stephen Fitzmeyer, MD

In this tutorial, we will be demonstrating how to use PHP to display patient data from a MySQL database. We will assume that you already have a MySQL database set up and running with patient information stored in it.

Step 1: Connect to the Database

The first step is to connect to the MySQL database using PHP. This can be done using the mysqli_connect() function. Replace “hostname”, “username”, “password”, and “database” with your own values:

<?php

    $conn = mysqli_connect(“hostname”, “username”, “password”, “database”);

    if (!$conn) {

        die(“Connection failed: ” . mysqli_connect_error());

    }

?>

Step 2: Retrieve Patient Data

Next, we will use PHP to retrieve the patient data from the MySQL database. This can be done using the mysqli_query() function to execute an SQL query. Replace “patients” with the name of your own patients table:

<?php

    $sql = “SELECT * FROM patients”;

    $result = mysqli_query($conn, $sql);

    if (mysqli_num_rows($result) > 0) {

        // output data of each row

        while($row = mysqli_fetch_assoc($result)) {

            echo “Patient ID: ” . $row[“patient_id”]. ” – Name: ” . $row[“name”]. ” – Age: ” . $row[“age”]. “<br>”;

        }

    } else {

        echo “0 results”;

    }

?>

This code will retrieve all the patient data from the “patients” table and display it on the screen. You can modify the SQL query to retrieve specific patient data based on criteria such as name, age, or date of birth.

Step 3: Close the Database Connection

Finally, we need to close the database connection using the mysqli_close() function:

<?php

    mysqli_close($conn);

?>

This ensures that the connection to the MySQL database is properly closed, freeing up resources and improving performance.

Conclusion

In this tutorial, we demonstrated how to use PHP to display patient data from a MySQL database. By connecting to the database, retrieving patient data using an SQL query, and closing the database connection, we were able to display patient data on the screen. This is just a basic example, but with further development and customization, you can create more advanced healthcare applications using PHP and MySQL.

Author: Stephen Fitzmeyer, M.D.
Physician Informaticist
Founder of Patient Keto
Founder of Warp Core Health
Founder of Jax Code Academy, jaxcode.com

Connect with Dr. Stephen Fitzmeyer:
Twitter: @PatientKeto
LinkedIn: linkedin.com/in/sfitzmeyer/

Scroll to top