How to display the Options (HTML) with the elements of the Database

0
Hello, I am trying to do the following: I want the elements that are registered in the database to appear inside a "Select - Option (FORM - HTML)".

Ex:

<body>
<?php
include("conexa.php");
$id = 80;
$pegadiv = $PDO->query("SELECT * FROM 'dividas' WHERE id_user = '$id'");
while($linha = $pegadiv->fetch(PDO::FETCH_ASSOC)){
$idConta = $linha['id'];
$nomeConta = $linha['descricao'];
echo "<br>";
}
?>
<form method="post" action="action.php">
<select name="conta">
    <option name="<?php $idConta ?>"> <?php echo $nomeConta?> </option>
</select>
<input type="submit" value="Excluir">
</form>
</body>

This is the way I'm doing, except that only the last account listed by the user appears.

    
asked by anonymous 17.09.2017 / 19:46

2 answers

2

If you do not understand why you are only getting the last record you will make this mistake again.

Look exactly at:

while($linha = $pegadiv->fetch(PDO::FETCH_ASSOC)){
    $idConta = $linha['id'];
    $nomeConta = $linha['descricao'];
    echo "<br>";
}

You have two variables, $idConta and $nomeConta , so imagine you do this:

foreach([1,2,3,4] as $numero){
    $idConta = $numero;
}

What will happen? The $idConta will be 1, then it will be 2, then it will be 3, then it will be 4 and it will end foreach . At the end you will have the last element, 4 .

One way to fix this is to do:

<body>
<?php
include("conexa.php");
$id = 80;
$pegadiv = $PDO->query("SELECT * FROM 'dividas' WHERE id_user = '$id'");

<select name="conta">
    <?php
    while($linha = $pegadiv->fetch(PDO::FETCH_ASSOC)){
    ?>
    <option name="<?= $linha['id'] ?>"> <?= $linha['descricao'] ?> </option>
    <?php
    }
    ?>
</select>

<input type="submit" value="Excluir">
</form>
</body>

In this way everything that is inside while will repeat.

    
18.09.2017 / 00:31
1

I'm going to make an adaptation in your code just for didactics, the content of the option needs to stay within the while.

<?php include("conexa.php"); ?>
<body>
<form method="post" action="action.php">
<select name="conta">    
<?php
$id = 80;
$pegadiv = $PDO->query("SELECT * FROM 'dividas' WHERE id_user = '$id'");
    while($linha = $pegadiv->fetch(PDO::FETCH_ASSOC)){
        echo "<option id=\"{$linha['id']}\" name=\"{$linha['id']}\">{$linha['descricao']}</option>";
    }
?>
</select>
<input type="submit" value="Excluir">
</form>
</body>

As I said, it's just a way to solve.

    
18.09.2017 / 00:18