Neven Grguric Neven Grguric -5 years ago 85
PHP Question

Displaying only last item in array

So i have dropdown menu which i want to fill in with items in array.Problem is that only thing in array is last item in database.
This is PHP:

$link = mysqli_connect("","cl38-baza","3g!cwDwxm","cl38-baza");
if(mysqli_connect_error()) {
die("Database Connection Error");
} else {
$query = "SELECT name FROM People ";
$result = mysqli_query($link,$query);

if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$names= array($row);

} else {
echo "no result!";


And HTML is:

<select class="form-control select2" style="width: 100%;">
<option selected="selected">Choose one</option>

foreach($names as $name) { ?>
<option value="<?php echo $name['name'] ?>"><?php echo $name['name'] ?></option>
} ?>


Thanks for help!

Answer Source

This line assigns value to $names

$names= array($row);

Instead you have to add to array in order to loop in HTML

$names[] = $row;

Also declare

$names = [];

above line

if(mysqli_num_rows($result) > 0) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download