skinmanater
skinmanater

Reputation: 7

How do I echo SQL data from database table into a <select> form?

I wonder if anyone can help.

I am trying to echo some SQL data into a <select> form with each <option> as a different row from the table.

For example if my table has two columns 'username' and 'category' and there are two rows for the same username, with the data:

"username: test, category: test1."

& second row as:

"username: test, category: test2."

How could I echo 'test1' and 'test2' as two options in a select form?

The table name is 'testtable' so my current $sql query is ("SELECT 'category' FROM 'testtable' WHERE 'username = \'$user\'")

$user is currently set to the $_SESSION['username']

Code examples would be really helpful and much appreciated. I just cant seem to get them to echo in examples I have found on forums.

Upvotes: 0

Views: 3282

Answers (5)

Satish Sharma
Satish Sharma

Reputation: 9635

try this

<select name="your_select_name" id="your_select_id">
    <option value="">Select</option>
    <?php
        $username = $_SESSION['username'];
        $res = mysql_query("SELECT `category` FROM `testtable` WHERE `username` = '$username' ") or die(mysql_error());
        while($row = mysql_fetch_assoc($res))
        {
            echo '<option value="'.$row['category'].'">'.$row['category'].'</option>';
        }
    ?>
</select>

UPDATE 2:

For distinct category use this

$res = mysql_query("SELECT DISTINCT(`category`) as category FROM `testtable` WHERE `username` = '$username' ") or die(mysql_error());

OR

$res = mysql_query("SELECT `category` FROM `testtable` WHERE `username` = '$username' GROUP BY category ") or die(mysql_error());

Upvotes: 1

user2632918
user2632918

Reputation:

You got from your query all rows:

<?php
$query = "SELECT category FROM testtable WHERE username = '" . $_SESSION['username'] ."'";
$result = mysql_query($query);
$options = array();
while($row = mysql_fetch_array($result))
{
    $options[] = "<option>" . $row['category'] . "</option>";
}
?>

<select>
    <?php echo implode("",$options); ?>
</select>

Upvotes: 1

user2641077
user2641077

Reputation: 159

<?php
$result = mysql_query($query);
echo "<select>";
while($row = mysql_fetch_array($result))
{
echo  "<option>".$row['category']."</option>";
}
echo "</select>";
?>

Upvotes: 0

user2936213
user2936213

Reputation: 1011

Try this:

<select>
  <?php while($row = mysql_fetch_array($result)
   {?>
   <option><?php echo $row['category'];?></option>
  <?php }?>
</select>

Upvotes: 0

n-dru
n-dru

Reputation: 9440

Your select query has an error: unpaired single quote before username, and single quotes surrounding category - is that possible that was the reason you couldn't do it?

Upvotes: 0

Related Questions