Method that takes all data returns empty JSON in the API

Asked

Viewed 268 times

0

I’m developing an API based on code from a publication I saw on the internet, source: https://www.w3jar.com/crud-rest-api-in-php-pdo/

This file has a condition, if I pass an ID it returns a good record, but when I’m just performing GET without the specific ID is not being returned anything to the list, it just comes empty. Someone would have a solution as help?

<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: access");
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Credentials: true");
header("Content-Type: application/json; charset=UTF-8");


// INCLUINDO BANCO DE DADOS E FAZENDO OBJETO
require 'database.php';
$db_connection = new Database();
$conn = $db_connection->dbConnection();

// Checar paramêtro ID ou não
if(isset($_GET['id']))
{
    //Se tem id como paramêtro
    $post_id = filter_var($_GET['id'], FILTER_VALIDATE_INT,[
        'options' => [
            'default' => 'all_cursostable',
            'min_range' => 1
        ]
    ]);
}
else{
    $post_id = 'all_cursostable';
}

// Fazer query SQL
// Se não houver id irá mostrar todos os cursos, caso contrário irá mostrar apenas um
$sql = is_numeric($post_id) ? "SELECT * FROM `cursostable` WHERE id='$post_id'" : "SELECT * FROM `cursostable`"; 

$stmt = $conn->prepare($sql);

$stmt->execute();

//Verificar se há algo para printar no BD
if($stmt->rowCount() > 0 && $stmt->rowCount() != null){
    // Criar POST array
    $posts_array = [];

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)){

        $post_data = [
            'id' => $row['id'],
            'cursos' => $row['cursos'],
        ];
        // Mandar registros POST para o $posts_array
        array_push($posts_array, $post_data);
    }
    //Mostrar POST/No formato JSON
    echo json_encode($posts_array);

}
else{
    //Se não houver nada no BD
    echo json_encode(['message'=>'Dados não encontrados.']);
}
?>
  • Debug to see if you are entering the if, if you have a day dump in the array $posts_array

  • Pedro, I’m sure we can help you, but with the code above, there’s not enough information to help you. With this, I suggest you to var_dump() in $stmt and show in your question. Second thing: Why are you using is_numeric()? Pass on this information that we can ascertain what you need

  • if(Empty($var)){ if empty... }

  • Hello guys, I will try this validation with var_dump, I am also a little lost in relation to the code because I want to learn how to develop an API with PHP through the source that is in the link I left. Really I’m not sure why it doesn’t bring the air and with all the bank results, but if I pass an ID, it returns the result normally.

  • Someone has an example of how a getAll request could work with PHP?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.