Database with php

4

I am trying to query the database with the following script:

<?php
        require("conexao.php");

        $exibir = mysql_query("SELECT * FROM produtos");
        while ($r = mysql_fetch_array($exibir)){
            $id = $r['id'];
            $nome = $r['nome'];
            $altura = $r['altura'];
            $peso = $r['peso'];
            $imc = $r['imc'];
        }    
?>
<?php
            echo "$nome <br/>";

?>

The code above was to return all table names, but only the last one returns me!

I would like to get back to me all the names !!

What's wrong?

    
asked by anonymous 06.01.2016 / 17:06

3 answers

4

The problem is that you are typing the name out of the loop repeat. The term "while" means "while" and represents a structure of repetition. In this case

Enquanto houver registro no banco de dados, faça:
    Faça Alguma coisa
Fim Enquanto

Move your echo into the loop.

    require("conexao.php");

    $exibir = mysql_query("SELECT * FROM produtos");
    while ($r = mysql_fetch_array($exibir)){
        $id = $r['id'];
        $nome = $r['nome'];
        $altura = $r['altura'];
        $peso = $r['peso'];
        $imc = $r['imc'];

        // Você deve escrever aqui o nome para aparecer todos os nomes.
         echo $nome . '<br />';
    }    
    
06.01.2016 / 17:11
2

To display all table values, leave the statement that prints something on the screen ( echo ) within the while and not out, otherwise only the last result will be displayed.

Problem code:

 while ($r = mysql_fetch_array($exibir)){
            $id = $r['id'];
            $nome = $r['nome'];
        }    
?>
<?php
            echo "$nome <br/>";

Right code:

<?php
        require("conexao.php");

        $exibir = mysql_query("SELECT * FROM produtos");
        while ($r = mysql_fetch_array($exibir)){
            $id = $r['id'];
            $nome = $r['nome'];
            $altura = $r['altura'];
            $peso = $r['peso'];
            $imc = $r['imc'];
            echo "$nome <br/>"; //<---- aqui está a diferença
        }    
    ?>

Recommended reading:

MySQL vs PDO - Which is the most recommended to use?

Why should not we use functions of type mysql_ *?

How to prevent SQL injection in my PHP code

    
06.01.2016 / 17:11
0

Notice that you created the while correctly, however, while While traversing all of your select records, your echo "$nome <br/>"; line must also come within the while so that as long as it finds a name it displays this name and so it does with all names found

 <?php
    require("conexao.php");

    $exibir = mysql_query("SELECT * FROM produtos");

    while ($r = mysql_fetch_array($exibir)){
        $id = $r['id'];
        $nome = $r['nome'];
        $altura = $r['altura'];
        $peso = $r['peso'];
        $imc = $r['imc'];

        echo "$nome <br/>";
    }               
?>
    
10.11.2017 / 17:49