List all data from a survey

Asked

Viewed 69 times

1

How to list all the data of this query, I can only show the first line but I want to query all and show them.

public function gerarCardapio(){
        try{
            $cat = "M";
            $sql = "SELECT * FROM alimentos WHERE id_usuario = :idUser AND categoria = :cat AND quantidade >0 ";
            $stmt = DB::prepare($sql);
            $stmt->bindParam('idUser', $_SESSION['user_id']);
            $stmt->bindParam('cat', $cat);
            $stmt->execute();//Executa o comano SQL
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            echo $stmt->rowCount();
        }catch (PDOException $e){
            echo $e->getMessage();
        }
    }
  • 1

    In the code, I don’t see where you’re returning or printing the result on the screen, other than the number of lines that were returned echo $stmt->rowCount();

  • The documentation is your friend, see example #2: http://php.net/manual/en/pdostatement.fetch.php#example-1058

2 answers

1

I noticed that you are returning the number of food field rows from the table using echo $stmt->rowCount();

Use $result->fetchAll(PDO::FETCH_ASSOC),

And also use : in the treatment of bindParam(:..., $....);

public function gerarCardapio(){
  try{
    $cat = "M";
    $sql = "SELECT * FROM alimentos WHERE id_usuario = :idUser AND categoria = :cat AND quantidade > 0 ";
    $stmt = DB::prepare($sql);
    $stmt->bindParam(':idUser', $_SESSION['user_id']);
    $stmt->bindParam(':cat', $cat);
    $stmt->execute();//Executa o comano SQL
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    var_dump($result);
  }catch (PDOException $e){
    echo $e->getMessage();
  }
}

1


As commented by @Knautiluz, you should use while.

# Apenas um exemplo de uso, pois não sei os nomes das colunas.
while($linha = $stmt->fetch(PDO::FETCH_ASSOC)){
    printf("id_usuario: %s categoria: %s", $linha['id_usuario'], $linha['categoria']);
}

thus remaining its method:

public function gerarCardapio(){
    try{
        $cat = "M";
        $sql = "SELECT * FROM alimentos WHERE id_usuario = :idUser AND categoria = :cat AND quantidade >0 ";
        $stmt = DB::prepare($sql);
        $stmt->bindParam(':idUser', $_SESSION['user_id']);
        $stmt->bindParam(':cat', $cat);
        $stmt->execute();//Executa o comano SQL
        # Apenas um exemplo de uso, pois não sei os nomes das colunas.
        while($linha = $stmt->fetch(PDO::FETCH_ASSOC)){
            printf("id_usuario: %s categoria: %s", $linha['id_usuario'], $linha['categoria']);
        }
    }catch (PDOException $e){
        echo $e->getMessage();
    }
}

You can see a basic example in tutorialspoint

I recommend that you read on documentation how to make use of the function bindParam.

References

Browser other questions tagged

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