user1371674
user1371674

Reputation: 3

How to make a dropdown with data from a mysql table?

I wanted to make a dropdown area by getting the values from a mysql table. This code does not seem to work; all it prints out is the box for the dropdown without the content, how can I get this to work? or is there an alternative procedure in doing this?

<?
$connection = mysql_connect("localhost", "root", "");
mysql_select_db("test", $connection);
$query = "SELECT full_name FROM test";
$names = mysql_query($query);
function dropDown($content, $result)
 {
while($row = mysql_fetch_row($result))
    {
        $name = $row[0];
        $content .= "<option value='$name'>$name</option>";
    }
 }
$content=<<<EOT
           <html>
              <body>
                 <select name="name">
EOT;

dropDown($content, $names)

$content.=<<<EOT
                 </select>
              </body>   
            </html>          


EOT;

echo $content;
?>

Upvotes: 0

Views: 2663

Answers (3)

newbie
newbie

Reputation: 1

<?php echo $form->dropDownList($model,'courseprefer', array(

'(*value in database table*'=>'displaying value',
 )); ?>

you can manually add them just make sure that the first value in array is in the database table.. :)

to avoid error!

Upvotes: 0

yasin
yasin

Reputation: 269

    here database details      
  mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

     $sql = "SELECT username FROM userregistraton";
        $result = mysql_query($sql);

         echo "<select name='username'>";
  while ($row = mysql_fetch_array($result)) {
   echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";}
   echo "</select>";


      here username is the column of my table(userregistration)
     it works perfectly

or simply the code is 
        <?
         $sql = "SELECT * FROM userregistraton ";
             $result = mysql_query($sql); ?>


 <select name="username" id="username">
<option value="">Select user</option>
    <?php
        while ($row = mysql_fetch_array($result))
        { ?>
          <option value="<?php echo $row['uid']?>"         <?php    if($row['uid']==$_POST["username"]) echo "selected"; ?> >
   <?php echo $row['username'];?></option>
   <?php
         } ?>

Upvotes: 0

ThiefMaster
ThiefMaster

Reputation: 318468

return the string. PHP is not C where you use out parameters just because they are sometimes handy.

function dropDown($result, $fieldName)
{
    $content = '';
    while($row = mysql_fetch_row($result)) {
        $name = $row[0];
        $content .= "<option value='$name'>$name</option>";
    }
    return '<select name="'.$fieldName.'">'.$content.'</select>';
}

$content = '<html><body>';
$content .= dropDown($names, 'name');

Upvotes: 2

Related Questions