I am trying to query a MySQL database and display the results on a php webpage as below,
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>
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'];'
<?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>';
?>
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 -->
<?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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.