Neven Grguric Neven Grguric - 4 months ago 7
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("79.170.44.77","cl38-baza","3g!cwDwxm","cl38-baza");
//LOADING DATA
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>
<?php

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

</select>


Thanks for help!

Answer

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) {
Comments