Listing data from a table with PHP

Asked

Viewed 2,582 times

1

Hello, I’m trying to make a list with data in a table with the code below, but I’m not getting it. I’ve done several ways, I’ve seen tutorials on the Internet and everything, however, it comes to nothing. On the server both local and external nothing appears, everything is white. Someone could let me know if there is an error in this code?

    <?php
    require_once("Conn.php");
    $conexao = conectar();

    $query = "SELECT * FROM tab_final";
        try{
            $selecionar = $conexao->prepare($query);
            $selecionar->execute();
            $select = $selecionar->fetchAll(PDO::FETCH_OBJ);
          foreach($select as $listar){
            echo "Times: ".$listar->Nome."<br />";
          }
        }catch(PDOException $e){
            echo $e->getMessage();

     }
    ?>

I even used the FETCH_ASSOC and changed the echo to be according to the same and nothing. I don’t know what else to do. If anyone can test and get it, please help me! Thanks in advance!

1 answer

1


It’s very simple to make a simple listing using PHP + Mysql. If you are a beginner, I advise you to first do everything on a page, then you can go organizing according to the pattern you want. See below for a simple example:

Example of connection:

<?php
// Instancia o objeto PDO
$pdo = new PDO('mysql:host=localhost;dbname=db', 'root', '');
// define para que o PDO lance exceções caso ocorra erros
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

The simplest way to execute a query would be using query as an example:

<?php
// executa a instrução SQL
$consulta = $pdo->query("SELECT fullname, email FROM user;");
?>

To obtain the data can be used a while thus traversing each line returned from the database:

<?php
while ($linha = $consulta->fetch(PDO::FETCH_ASSOC)) {
    // aqui eu mostro os valores de minha consulta
    echo "Fullname: {$linha['fullname']} - email: {$linha['E-mail']}<br />";
}
?>

I put the full code on Github as Query.php. for the record.

You can see more details on PHP Data Objects and PDO:Query.

  • Thank you very much, Ack. I studied your code and got it, now you’re listing the data from the table.

Browser other questions tagged

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