How to show Options (HTML) with database elements

Asked

Viewed 199 times

0

Hello, I want to do the following: I want the elements that are registered in the database to appear within 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 it, only this way appears the last account listed by the user.

  • your options need to stay within while, the way it is you are getting some result?

  • I get it. But only the last registered.

  • When I put inside the looping creates a select for each registered item

  • Did you come to test my code? as I mentioned before the option needs to be inside the looping, the <select> tag needs to be outside, respecting <select><looping></select>

2 answers

2


If you don’t understand why you are just getting the last record you will make this mistake again.

Note exactly in:

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 will be 2, then will be 3, then will be 4 and will end the 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>

That way everything inside the while will repeat.

1

I will make an adaptation in your code just for didactics, the content of the option needs to stay inside 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 is just a way to solve.

Browser other questions tagged

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