PHP array explode result shows only last value in form select while print function shows all values. The HTML part should display all values in drop down. Currently, it's showing only the last value.
MYSQL
Table Name: op_subject_combination
Id = 1 and its op_subject_combo_sub1 values are (chemistry, physics, mathematics)
PHP Part
<?php
$select_enquiry="SELECT * FROM op_subject_combination where id = '1' order by id desc limit 20";
$sql=$dbconn->prepare($select_enquiry);
$sql->execute();
$wlvd=$sql->fetchAll(PDO::FETCH_OBJ);
if($sql->rowCount() > 0){
foreach($wlvd as $rows){
$str = $rows->op_subject_combo_sub1;
$arr = explode( ",", $str ) ;
foreach ($arr as $row1)
?>
HTML Part
<div class="form-group">
<label for="exampleInputEmail1">Session Name</label>
<select class="form-control" id="op_subject_combo_session" name="op_subject_combo_session" >
<option selected><?php echo $rows4->st_center; ?></option>
<option>--------</option>
<option><?php echo $row1 ;?></option>
<?php }} ?>
</select>
</div>
Your nesting is wrong. The foreach should enclose only the <option
> like below. You should also set selected
on a single option, based on some criteria. And value=""
for every option. Kindof, take a paper and pen and set down in natural language what you are trying to do and what the output should be.
<?php
$select_enquiry="SELECT * FROM op_subject_combination where id = '1' order by id desc limit 20";
$sql=$dbconn->prepare($select_enquiry);
$sql->execute();
$wlvd=$sql->fetchAll(PDO::FETCH_OBJ);
if($sql->rowCount() > 0){
foreach($wlvd as $rows){
?>
<div class="form-group">
<label for="exampleInputEmail1">Session Name</label>
<select class="form-control" id="op_subject_combo_session" name="op_subject_combo_session" >
<?php
$str = $rows->op_subject_combo_sub1;
$arr = explode( ",", $str ) ;
foreach ($arr as $row1) {
?>
<option <?=$row1==$rows4->st_center?' selected':''?>>
<?php echo $row1; ?>
</option>
<?php
}
?>
<option>--------</option>
</select>
</div>
<?php
}
}
?>