Take the names of a form on a php page and put it in a select list on another php page

Asked

Viewed 808 times

2

I have 2 pages cadastrar_loja.php and cadastra_documento.php. In cadastrar_loja.php there is a text field called Nome da loja, I’d like to take that name from the database and insert it into a <select> on the page cadastrar_documento.php. Thus creating a list within the <select> with all the names of the registered stores.

The application is in PHP and my bank is mysql, I’m spinning in the xampp.

How can I do that?

  • Yes it is possible to do that, do you have any code? started?

  • 1

    Welcome to SOPT @Túlio, Teria as [Edit] your post and add the code you are using, so we can analyze and suggest a change. Thank you.

2 answers

3

Boa Tarde Túlio,

Another and safer option would be to use PDO. It would look something like this:

<?php
try {
    $conn = new PDO('mysql:host=enderecodohost;dbname=nomedodb', $usuario, $senha);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

$stmt = $conn->prepare('SELECT id, nome FROM lojas ORDER BY nome ASC');
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);

?>
<select name="lojas">
    <?php foreach($data as $row) { ?>
        <option value="<?= $row['id']; ?>"><?= $row['nome']; ?></option>
    <?php }?>
</select>

You can still pass PDO::FETCH_CLASS as a function parameter fetchAll(), and work with OO. In this case your query return would be objects instead of arrays.

I hope I’ve helped!

  • Thanks man, but I did without PDO even so, thanks, added knowledge.

1


How you are using mysql (I advise you to study about mysqli or PDO), first select from the table cadastrar_loja on the page cadastrar_documento.php:

$consulta = mysql_query("SELECT id,nome FROM cadastrar_loja ORDER BY nome DESC");

Then do the <select>:

<select class="form-control" name="txtNomeLoja" >
    <?php while ($dados = mysql_fetch_array($consulta)) { ?>
      <option value=<?=$dados['id']?>> <?=$dados['nome']?> </option>
    <?php } ?>
</select>   

The value of <select> will receive the id of the store and to the user will be displayed the nome store.

  • O if it is starting pq using mysql_*(removed) ? needs the distinct even?

  • didn’t understand @rray? doesn’t use distinct in mysql?

  • Store name should not have repeated values.

  • 1

    Thank you very much. Thank you very much!

Browser other questions tagged

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