How to display all the results of a SELECT in PHP?

Question:

I've done this code all by myself, but I'm having trouble displaying all the results one below the other.

    <?php include 'conexao.php'; ?>
<html>
    <head>
        <title>GMB Mineração e Comércio LTDA</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <link type="text/css" href="css/default.css"/>
    </head>
    <body>    
        <h1>Clientes</h1>
        <fieldset class="row2">
          <legend><font color="white">-</font></legend>
            <p>
                <?php
                    $query = "SELECT * from clientes";
                    $result = mysql_query($query);
                    $fetch = mysql_fetch_row($result);
                    $final = $fetch[0];
                ?>
            </p>
        </fieldset>
    </body>
</html>

Answer:

So:

<?php
    $query = "SELECT * from clientes";
    $result = mysql_query($query);
    while($fetch = mysql_fetch_row($result)){
        echo "<p>". $fetch[0] . " - " . $fetch[1] . " - " . "</p>";
    }
?>

There are a number of other ways to do this. It depends on the specific need.

You could do something like this (most recommended (but it's just an example, I don't know how it's structure):

<?php
    $query = "SELECT cnpj, nome from clientes";
    $result = mysql_query($query);
    while($fetch = mysql_fetch_row($result)){
        echo "<p>". $fetch[0] . " - " . $fetch[1] . " - " . "</p>";
    }
?>

This way you bring only the fields you are going to use. But if you are going to put all the fields in the table yourself, you can do this:

<?php
    $query = "SELECT * FROM clientes";
    $result = mysql_query($query);
    while($fetch = mysql_fetch_row($result)){
        echo "<p>";
        foreach ($fetch as $value) {
            echo $value . " - ";
        }
        echo "</p>";
    }
?>

I put it on GitHub for future reference .

It can still be done in a better way. But I think the idea is just to give you the basic idea, the ideal is to set this up using a <table> or a more structured way of organizing this data. But I think you should take it one step at a time.

Ideally, you would also use MySQLi which is a more modern and recommended API.

Scroll to Top