Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

How to retrieve data from MySQL database using PHP ?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

There are steps to understand for retrieving the data from the MySQL database


Now we understand each and every step as shown below.

 Example 1: In this. we use PHPMyAdmin for the database handling. Start the server in the XAMPP as shown in the below image

Making sure that both Apache and MySQL are showing green color, means that the server is working.


After that create the database in the PHPMyAdmin. Open the below URL.


Creating the database:

creating the database in MySQL PHPMyAdmin

Create the table: Execute the SQL query in the “gfg” database.

     name varchar(20), 
    branch varchar(20),
    roll_no INT

Enter the data in the table.

INSERT INTO `student` ( `name`, `branch`, `roll_no`)  
    VALUES ( 'Rohan', 'CSE', '1' );

After the data is inserted, the table will look like this.

After entering the data in the table

PHP Code: Run the PHP script as shown below to fetch the data from the database.


   $servername = "localhost";
   $username = "root";
   $password = "";
   $dbname = "gfg";
   // connect the database with the server
   $conn = new mysqli($servername,$username,$password,$dbname);
    // if error occurs 
    if ($conn -> connect_errno)
       echo "Failed to connect to MySQL: " . $conn -> connect_error;
    $sql = "select * from student";
    $result = ($conn->query($sql));
    //declare array to store the data of database
    $row = []; 
    if ($result->num_rows > 0) 
        // fetch all data from db into array 
        $row = $result->fetch_all(MYSQLI_ASSOC);  
<!DOCTYPE html>
    td,th {
        border: 1px solid black;
        padding: 10px;
        margin: 5px;
        text-align: center;
                <th>Roll Number</th>
               foreach($row as $rows)
                <td><?php echo $rows['name']; ?></td>
                <td><?php echo $rows['branch']; ?></td>
                <td><?php echo $rows['roll_no']; ?></td>
            <?php } ?>


Output of the above PHP script

My Personal Notes arrow_drop_up
Last Updated : 10 Mar, 2022
Like Article
Save Article
Similar Reads
Related Tutorials