0

I am trying to create a select box that will display several times on the page, where the options are populated by my SQL query. I am able to get this to display once but when I try to create a second, identical select box, there are no options in the dropdown box. Here is what I have working:

 <?php include_once "app/init.php";
      $dataQuery = $db->prepare("
      SELECT column FROM dataType");

  $dataQuery->execute([]);
  $dataTypes = $dataQuery->rowCount() ? $dataQuery : [];
?>

<div>
   <select>
      <?php foreach($dataTypes as $dataType): ?>
          <option>
               <?php echo $dataType['dataType']; ?>
          </option>
      <?php endforeach; ?>
    </select>
 </div>

But when I try to add a second select box, it it blank. I am creating a table that will have this select box on every row for the user to select a data type so I need to recreate this dynamically several times. I am new to php, so what is the best way to go about this?

My init.php to show using PDO:

<?php session_start();
  $_SESSION['user']=1;
  $db = new PDO ('mysql:dbname=myDB;host=localhost', 'root', 'root');
  if(!isset($_SESSION['user'])) {
     die('You are not signed in');
 };
heat222
  • 99
  • 8
  • You're asking for a [cursor](http://stackoverflow.com/questions/1155211/what-is-pdo-scrollable-cursor) type you can rewind. No idea if MySQL or PDO support that. However, it's often a good idea to release the result set as soon as possible (if not for performance, at least from the design standpoint). So I'd really store the information in a variable before I use it. – Álvaro González Jan 03 '17 at 17:52

1 Answers1

2

You can only loop through the PDO statement once, so you should put the result in a temporary array.

Instead of:

$dataTypes = $dataQuery->rowCount() ? $dataQuery : [];

Do

$dataTypes = $dataQuery->fetchAll(\PDO::FETCH_ASSOC);
Evert
  • 93,428
  • 18
  • 118
  • 189