meddy
meddy

Reputation: 395

Retrieving data from Mysql and storing in option html tag

Hey guys i'm stuck on this question. What I'm trying to do is retrieve some data from MYSQL and store it in an option tag. Here is my code.

<?php
$user = "admin";
$password = "";
$db = "test";
$host = "localhost";
$cxn = mysqli_connect($host, $user, $password, $db);

$query = "SELECT ARTIST FROM music";
$results = mysqli_query($cxn, $query) or die("Connection could not be established");

echo "<select name='mediaType'>";
while ($row = mysqli_fetch_assoc($results))
{
    extract($row);
    echo "<option value=''>$row</option>\n";                                        
}
echo "</select>";
?>

After preforming this function the output in the option tag is "Array" for all options in the select element. I tried storing the data from the php variable $row into an array then looping threw that array and echoing out each index in the array, but the results were the same. May someone plz provide me some guidance on this issue. Thanks all who help.

Upvotes: 0

Views: 2927

Answers (2)

wmassingham
wmassingham

Reputation: 381

Per the other users, extract() is not what you want here. $row is an array where the keys are your column names. Use something like this:

while ($row = mysqli_fetch_assoc($result)) {
    echo '<option value="">'.$row['ARTIST'].'</option>';
}

Note how I changed the quotes; the array operator doesn't work within a double-quoted string.

And in the future, to inspect the contents of a variable, look into using var_dump(), it's great for seeing what's going on behind the scenes.

Edit: oh, and if your table has a numeric primary key ID, you should probably use that as the value for your select, to protect yourself against changing names or human-input typos.

Upvotes: 1

Parag Tyagi
Parag Tyagi

Reputation: 8960

Why not simply do:

echo "<select name='mediaType'>";
while ($row = mysqli_fetch_assoc($results))
{
    echo "<option value='".$row['ARTIST']."'>".$row['ARTIST']."</option>";
}
echo "</select>";

Upvotes: 0

Related Questions