Mon Aug 28 2023

Fetch MySQL Data

Fetch MySQL Data

File Name: fetch-mysql-data.php

<?php
    $host = "localhost";
    $user = "root";
    $password = "Qwerty@2022";
    $database = "geekboots";
    $query = "SELECT * FROM user";


    // Object Oriented Way
    $connect = new mysqli($host, $user, $password, $database);

    if($connect->error)
        die("Failed to connect with database");
    
    echo "Database connected!";

    $result = $connect->query($query);

    if($result->num_rows > 0) {
        while($row=$result->fetch_object()) {
            echo "<br /><br />Id: ".$row->id;
            echo "<br />First Name: ".$row->fstName;
            echo "<br />Last Name: ".$row->lstName;
            echo "<br />E-mail: ".$row->email;
        }
    } else {
        echo '<br />No Data Found!';
    }


    $connect->close();


    // Procedural Oriented Way
    $connect = mysqli_connect($host, $user, $password, $database);

    if(!$connect)
        die("Failed to connect with database!");

    echo "Database connected!";

    $result = mysqli_query($connect, $query);

    if(mysqli_num_rows($result) > 0) {
        while($row=mysqli_fetch_assoc($result)) {
            echo "<br /><br />Id: ".$row['id'];
            echo "<br />First Name: ".$row['fstName'];
            echo "<br />Last Name: ".$row['lstName'];
            echo "<br />E-mail: ".$row['email'];
        }
    } else {
        echo '<br />No Data Found!';
    }


    mysqli_close($connect);
?>

We use cookies to improve your experience on our site and to show you personalised advertising. Please read our cookie policy and privacy policy.