Home > Back-end >  How to Query a MySQL database and display results using a dropdown in PHP
How to Query a MySQL database and display results using a dropdown in PHP

Time:11-28

I am trying to query a MySQL database and display the results on a php webpage as below ,

enter image description here however i get the error Parse error: syntax error, unexpected 'position' (T_STRING) in C:\wamp64\www\webform\display-data.php on line 5.Below is my PHP code

<?php 
$mysqli = mysqli_connect('localhost','staff','staff','webform');
$query ="SELECT position FROM entries";
$result = $mysqli->query($query);
if($result->num_rows> 0){
  $options= mysqli_fetch_all($result, MYSQLI_ASSOC);
}
<?php 


<?php
include("dbconfig.php");
include("fetch-data.php");
?>
<select name="position">
   <option>Select staff</option>
  <?php 
  foreach ($options as $option) {
  ?>
    <option><?php echo $option['position']; ?> </option>
    <?php 
    }
   ?>
</select>

CodePudding user response:

Move option tag inside your echo so it should be like this:

<select name="position">
   <option>Select staff</option>
   <?php 
       foreach ($options as $option) {
          echo "<option>$option['position'];</option>";
       }
   ?>
</select>

That should echo option tag for each $option. You can also add value attribute by adding value='$option['position'];'

CodePudding user response:

<?php
include("dbconfig.php");
include("fetch-data.php");

echo'<select name="position">
 <option>Select staff</option>'; 
  foreach ($options as $option) { 
   echo'<option value='.$option['position'].'>'.$option['position'].'</option>';
  } 
echo'</select>';

?>

CodePudding user response:

You're missing a quote in the code. Change include("fetch-data.php); to include("fetch-data.php");

  • Related