Adrian Fischer Adrian Fischer - 1 year ago 65
PHP Question

Populate more than one drop down using the same mysql query

I have form with a number of drop boxes which have the numbers 1-5 in them. I can use this code to populate a drop down but was wondering if I can somehow only make the call to the db once but populate all the drop downs that use the same numbers?


$sql = "SELECT * FROM riskNumDrop";
$result = $conn->query($sql);
if (!$conn->query($sql)) {
echo "query failed: (" . $mysqli->errno . ") " . $mysqli->error;
echo '<select class="assess" name="precontcons" style="width:4em">' ;
while($row = $result->fetch_assoc()){echo '<option value='. $row['riskNumDrop'] .'>'.$row['riskNumDrop'].'</option>';}
?> </select>

So Ideally, I generate the output once and reuse it multiple times. Im guessing an array (which $result already is) but how do I populate a drop down from it? TIA

Answer Source

Saving as a string would save you the processing of having to loop through the same data generating the same output multiple times. If this is what you want, you could do the following.


echo '<select  class="assess" name="precontcons"   style="width:4em">' ;
while($row = $result->fetch_assoc()){echo '<option value='.   $row['riskNumDrop'] .'>'.$row['riskNumDrop'].'</option>';}
?> </select>


$drop = '<select  class="assess" name="precontcons"   style="width:4em">' ;
while($row = $result->fetch_assoc()){
  drop .= '<option value='.   $row['riskNumDrop'].'>'.$row['riskNumDrop'].'</option>';
$drop .= '</select>';

Then you can echo $drop several times if you want.

If for whatever reason you want different select attributes, you could just save the options list and print the select around that, like this:

$dropOptions = "";
while($row = $result->fetch_assoc()){
  $dropOptions .= '<option value='.   $row['riskNumDrop'].'>'.$row['riskNumDrop'].'</option>';

Then just echo '<select class="foo" name="bar">'.$dropOptions.'</select'>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download