Skip to content Skip to sidebar Skip to footer

Retrieving Data Through Mysql Using Function And Use In The Select Box?

i write a program to retrieve the data through MySQL using function now i have a problem that how i use it in the select box? Code for this is given below, function selectdata(){ $

Solution 1:

Do like this

function selectdata(){
   $select="SELECT * FROM table_name";

   $run=mysql_query($select);
   $field_name = '';
   while($fetch=mysql_fetch_array($run)){
       $field_name.="<option value=''>" . $fetch['field_name'] . "</option>";
   }
   return $field_name;
}

And in html

<select name="office_name">
<?php echo selectdata(); ?>
</select>

Solution 2:

That's because you're echoing your string into one option value. A better way would be to return an array from selectdata() and then loop through it in your html like:

function selectdata(){
    $select="SELECT * FROM table_name";

    $run=mysql_query($select);
    $fields = array()
    while($fetch=mysql_fetch_array($run)){
        $fields[] = $fetch['field_name'];
    }
    return $fields;
}

And then

<select name="office_name">
    <?php foreach(selectdata() as $option): ?>
    <option value="<?php echo $option; ?>"><?php echo $option; ?></option>
    <?php endforeach; ?>
</select>

This way, you're keeping HTML out of your PHP.


Solution 3:

Try this one..Not sure the syntax is correct.

function selectdata(){
$select="SELECT * FROM table_name";

$run=mysql_query($select);

while($fetch=mysql_fetch_array($run)){
 $field_name.= "<option value=>" .$fetch['field_name']."</option>";
}
return $field_name;
}

HTML:

<select name="office_name">
<?php echo selectdata(); ?>
</select>

Solution 4:

<?php
$query = mysql_query("YOUR QUERY HERE"); // Run your query

echo '<select name="DROP DOWN NAME">'; // Open your drop down box

// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_array($query)) {
   echo '<option value="'.$row['something'].'">'.$row['something'].'</option>';
}

echo '</select>';// Close your drop down box





?>

Solution 5:

You can use as following sample,

<?php
$sql = "SELECT * FROM terms";
$result = mysql_query($sql) or die(mysql_error());

while ($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
   $term[$row{'term_id'}] = $row{'term_name'};
}
?>
    <select id="mass_term"  name="mass_term" style="width:125px;" >
   <?php foreach($term as $key=>$value){ ?>
      <option <?php echo ($key==$termid)?'selected="selected"':'' ?> value="<?php echo $key; ?>"><?php echo $value; ?></option>
   <?php } ?>
    </select>

Post a Comment for "Retrieving Data Through Mysql Using Function And Use In The Select Box?"