dapperwaterbuffalo
dapperwaterbuffalo

Reputation: 2748

Populate dropdown with MySQL query results (PHP/MySQL)

so as the title says.....

here is the code I currently wrote thinking it would work and it doesnt :(

note my session userid etc is working as I can get it to print out in another field in the form so thats not the problem, but my dropbox just seems to have nothing in it. (i have created the data on the database with the user_id matching of which I am logged in with)

$userid = $_SESSION['myuserid'];
//run query to database
$query = "SELECT * FROM test_groups_tb WHERE user_id='$userid'";
mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($query))
    {
    $dd .= "<option value='{$row['group_id']}'>{$row['group_name']}</option>";
    } 

this is then used in the html:

<select name="t_group"><? echo $dd; ?></select>

can somebody help me out?

thanks

Upvotes: 2

Views: 7566

Answers (3)

anothershrubery
anothershrubery

Reputation: 20993

$query is a string and therefore you cannot get any results from it. You should do something like:

$query = "SELECT * FROM test_groups_tb WHERE user_id='$userid'";
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($result))
{
    $dd .= "<option value='{$row['group_id']}'>{$row['group_name']}</option>";
} 

Upvotes: 3

Codecraft
Codecraft

Reputation: 8296

Personally, I always drop out of a string when i'm adding variables.. I know you don't have to do it depending on how you're set up, but my line would be:

$dd .= "<option value='".$row['group_id']."'>".$row['group_name']."</option>";

I'd also get rid of the inevitable notice by setting $dd = "" before trying to add to it, if you care about such things.

Check that your query is a resource (echo $query - expect 'resource id #nn') and that it is producing any rows [ echo mysql_num_rows($query); ]

Upvotes: 0

TJHeuvel
TJHeuvel

Reputation: 12608

It doesnt work because $query is a string. You should assign the result of mysql_query to the $query variable.

If you had error reporting on you would have seen an error like mysql_fetch_assoc expects parameter 1 to be resource, string given.

Upvotes: 2

Related Questions