PHP MySQL Connection Issue: Unable to Retrieve Data from Database

Discussion in 'PHP' started by Vishal Singh, 1 Sep 2023.

  1. Vishal Singh

    Vishal Singh New Member

    Joined:
    8 Aug 2023
    Messages:
    10
    Likes Received:
    0
    Reputations:
    0
    I'm facing a problem while trying to establish a connection between PHP and MySQL to retrieve data from a database. I'm using the mysqli extension for PHP, but I'm not able to fetch the expected results. Here's a simplified version of my code:
    PHP:
    <?php
    $servername 
    "localhost";
    $username "root";
    $password "";
    $database "mydatabase";

    // Create connection
    $conn = new mysqli($servername$username$password$database);

    // Check connection
    if ($conn->connect_error) {
        die(
    "Connection failed: " $conn->connect_error);
    }

    // Attempt to fetch data
    $query "SELECT * FROM mytable";
    $result $conn->query($query);

    if (
    $result->num_rows 0) {
        while(
    $row $result->fetch_assoc()) {
            echo 
    "ID: " $row["id"] . " - Name: " $row["name"] . "<br>";
        }
    } else {
        echo 
    "No data found.";
    }

    $conn->close();
    ?>
    When I run this script, I get the "No data found." message even though I have data in the mytable table. I've confirmed my database credentials and table name, but I can't figure out what's causing this issue.

    Could someone please review my code and provide insights into what might be causing this problem? Is there a common mistake I might be overlooking or any debugging steps I should take to diagnose the issue? Any help would be greatly appreciated. Thank you!
     
  2. b3

    b3 Banned

    Joined:
    5 Dec 2004
    Messages:
    2,174
    Likes Received:
    1,157
    Reputations:
    202
    try with debug
    PHP:
    <?php
    // debug ON
    mysqli_report(MYSQLI_REPORT_ERROR MYSQLI_REPORT_STRICT);
    error_reporting(E_ALL);


    $servername "localhost";
    $username "root";
    $password "";
    $database "";

    // Create connection
    $conn = new mysqli($servername$username$password$database);

    // Check connection
    if ($conn->connect_error) {
        die(
    "Connection failed: " $conn->connect_error);
    }

    // Attempt to fetch data
    // $query = "SELECT * FROM mytable";

    $query "SHOW DATABASES;";
    $result $conn->query($query);

    var_dump($result->num_rows);



    /*
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            echo "ID: " . $row["id"] . " - Name: " . $row["name"] . "<br>";
        }
    } else {
        echo "No data found.";
    }
    */



    $conn->close();
    ?>
     
Loading...
Similar Threads - MySQL Connection Issue
  1. GAiN
    Replies:
    3
    Views:
    7,324