skip to Main Content

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:wamp64wwwwebformdisplay-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>

3

Answers


  1. 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'];'

    Login or Signup to reply.
  2. <?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>';
    

    ?>

    Login or Signup to reply.
  3. I just found your problem. Just separate your file as my below code and check.

    <!-- Database connection file code (dbconfig.php) -->
    <?php
    // $mysqli=mysqli_connect(hostname, username, password, databaname)
    $mysqli = mysqli_connect('localhost', 'staff', 'staff', 'webform');
    ?>
    
    <!-- Fetch data file code (fetch-data.php) -->
    <?php
    $query = "SELECT position FROM entries";
    $result = $mysqli->query($query);
    if ($result->num_rows > 0) {
        $options = mysqli_fetch_all($result, MYSQLI_ASSOC);
    }
    ?>
    
    <!-- Your display dropdown file (index.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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search