Get names of a form in a php page and put it in a select type list on another php page [closed]

2

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

The application is in PHP and my bank is mysql , I'm running in xampp .

How can I do this?

    
asked by anonymous 25.01.2016 / 19:44

2 answers

1

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

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

Then do <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 for the user the nome of the store will be displayed.

    
25.01.2016 / 20:03
3

Good afternoon, Túlio,

Another, and safer, option would be to use the 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 parameter of the fetchAll () function, and work with OO. In this case your query return would be objects instead of arrays.

I hope I have helped!

    
25.01.2016 / 20:33