How to place database information in a select field in PHP

Asked

Viewed 426 times

0

I have a page that connects in the database and brings information correctly, however I would like to put information in a form using the select field, but I’m having some difficulties if someone can help me follow my code.

<?php
require_once 'init.php';

// abre a conexão
$PDO = db_connect();

// SQL para selecionar os registros
$sql = "SELECT cliente FROM clientes";

// seleciona os registros
$stmt = $PDO->prepare($sql);
$stmt->execute();

?>

<html>
<head>
    <meta charset="utf-8">
    <title>Lab</title>
</head>
<body>
    <h1>Lab</h1>

    <?php while ($user = $stmt->fetch(PDO::FETCH_ASSOC)): ?>
    <?php echo $user['cliente'] ?>
    <?php endwhile; ?>

</body>
</html>

2 answers

4


To make a select with your data:

<select>
  <?php while ($user = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
      <option value="<?php echo $user['cliente'] ?>">
        <?php echo $user['cliente'] ?>
      </option>
  <?php }  ?>
</select>
  • Thank you worked right however missed in opening the first line o {

  • Really, I’ll edit here.

-2

<select>
<?php 
    while ($user = $stmt->fetch(PDO::FETCH_ASSOC)){
        echo '<option value="'.$user['cliente'].'">'.$user['cliente'].'</option>';
    }
?>
</select>

Browser other questions tagged

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