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

functionselectdata(){
   $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

<selectname="office_name"><?phpecho 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:

functionselectdata(){
    $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

<selectname="office_name"><?phpforeach(selectdata() as$option): ?><optionvalue="<?phpecho$option; ?>"><?phpecho$option; ?></option><?phpendforeach; ?></select>

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

Solution 3:

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

functionselectdata(){
$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:

<selectname="office_name"><?phpecho selectdata(); ?></select>

Solution 4:

<?php$query = mysql_query("YOUR QUERY HERE"); // Run your queryecho'<select name="DROP DOWN NAME">'; // Open your drop down box// Loop through the query results, outputing the options one by onewhile ($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) ordie(mysql_error());

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

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