0

What am I doing wrong here? When it populates the options it shows $name[0] and not the info from the DB. Though the correct number of options seem to be available.

<?php
//connect to database
$conn = mysqli_connect("example.com", "timemin", "Pass123", "timesheet");

//query database for items to populate
$sql = "SELECT DIS_NAME, NAME FROM INVITEM";
$query = mysqli_query($conn, $sql);

echo '<select>';
echo '<option value="">Choose your favorite fruit</option>';
while($name = mysqli_fetch_assoc($query)){
echo '<option value="' . '$name[1]' . '">' . '$name[0]' . '</option>';
}
echo '</select>';
echo $query;
?>
Elegance
  • 7
  • 3

2 Answers2

2

Should be as follows, you quoted variables, that was the problem.

echo '<option value="' . $name['DIS_NAME'] . '">' . $name['NAME'] . '</option>';

Also as RiggsFolly mentioned, you used fetch_assoc so the array keys will be named accordingly DIS_NAME and NAME. Credit to RiggsFolly for spotting this.

DeDee
  • 1,972
  • 21
  • 30
2

In php, there are two types of quotes: single quotes and double quotes. Single quotes will not parse variables, double quotes will.

If you do want to use quotes, you could do something like this:

echo "<option value="."$name[1]".">$name[0]</option>";

So here, the double quotes will tell php to parse the variable names

However, I would recommend doing this:

echo '<option value="' . $name[1] . '">' . $name[0] . '</option>';

See this SO post for more.

Community
  • 1
  • 1
Iowa15
  • 3,027
  • 6
  • 28
  • 35
  • use `print_r($name);` to check your array. If there's nothing you have error in your SQL. If there is records, use array key names like `$name['firstname']`. – Aleksandar Aug 26 '15 at 23:18