Reputation: 791
I have a PHP script to populate drop down menu with results obtained from database the problem I am having is that only the last result is displayed in drop down menu. I recon it is because the while loop that gets all the results overwrites the variable that stores a string every time is runs.
I have tried to find a solution to fix it but ending up in a dark corner with no solution
Php Code:
$sql2 = "SELECT id, course, location FROM courses WHERE course LIKE '%Forex%' OR course LIKE '%forex%'";
$query2 = mysqli_query($link, $sql2);
$opt = '<select id="Forex" name="Forex">';
$opt1 = '<option value="">Select Forex Workshop</option>';
while($result2 = mysqli_fetch_assoc($query2)){
//I belief the $opt2 variable is overwritten every time the loop runs
$opt2 = '<option value="">'.$result2['course'].'</option>';
print_r($opt2);
}
$opt3 = '</select>';
return $opt.$opt1.$opt2.$opt3;
}
I might be wrong and the issue might be elswhere in the code but when i print_r($result2) all the correct results are there
Upvotes: 3
Views: 442
Reputation: 5135
You need to concatenate the each value with existing variable in the loop
**$opt2 .= '<option value="">'.$result2['course'].'</option>';**
Upvotes: 1
Reputation: 2475
Yes, you need to append each value:
$opt2 .= '<option value="">'.$result2['course'].'</option>';
You should also initialise $opt2 before you start the loop.
$opt1 = '<option value="">Select Forex Workshop</option>';
$opt2 = "";
Upvotes: 2
Reputation: 23978
Just add a .
$opt2 .= '<option value="">'.$result2['course'].'</option>';
^
Your variable is reinitializing, it should be concatenated.
So, the final code should be:
$opt2 = '';
while($result2 = mysqli_fetch_assoc($query2)){
//I belief the $opt2 variable is overwritten every time the loop runs
$opt2 = '<option value="">'.$result2['course'].'</option>';
print_r($opt2);
}
$opt3 = '</select>';
return $opt.$opt1.$opt2.$opt3;
Upvotes: 3