PHP GET Query returning null on a database with data - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Sunday, November 5, 2023

PHP GET Query returning null on a database with data

I have a php script to query from a table LABCPD which has one entry, however the GET call in POSTMAN is retuning status OK with no errors but not returning any data, there are no syntax errors or permission / access issues:

Script:

if ($_SERVER['REQUEST_METHOD'] === 'GET'){
    if(isset($_GET['id'])) {
        /// Sfaely escape the user input and use a prepared statement
        $id = $conn->real_escape_string($_GET['id']);

        // Prepare an SQL statement with a placeholder
        $stmt = $conn->prepare("SELECT * FROM $table WHERE id = ?");

        // Bind the escaped user input to the placeholder in the SQL statement
        $stmt->bind_param("i",$id);

        // Execute the prepared statement
        $stmt->execute();

        // Get the result of the query
        $result = $stmt->get_result();

        // Fetch the data as an associative array
        $data = $result->fetch_assoc();

        // Close the prepared statement
        $stmt->close();
    } else {
        $data = array();

        // Prepare an SQL statement to fetch all rows
        $stmt = $conn->prepare("SELECT * FROM $table");

        // Execute prepared statement
        $stmt->execute();

        // Get the result of the query
        $result = $stmt->get_result();

        while ($d = $result->fetch_assoc()){
            $data[] = $d;
        }

        // Close the prepared statement
        $stmt->close();
    }

    // Return the JSON data
    exit(json_encode($data, JSON_THROW_ON_ERROR, 512));
}

Database has one entry: Database with one row

My question is does it look like there is an issue with PHP snippet or could I be missing something else?



source https://stackoverflow.com/questions/77423291/php-get-query-returning-null-on-a-database-with-data

No comments:

Post a Comment