user580950 user580950 - 5 months ago 11
SQL Question

Repeat drop down boxes - 20 in Total - Mysql - PHP

I have 20 dropdown box which queries a single table and same field, I wrote the following query which works great. I am sure that there is a certain way to optimize this repetitive drop-down boxes, which I am not aware of.

Shall i write an function and the pass parameters from each

<select><? functioname() ?></select>

enter image description here

<div class="form-group">
<label>Split 1</label>
<select class="form-control required" name='distance[]' id='distance' >
<option value="-1">Select Distance</option>
<?php
$plan_sql="select * from mytable";
$plan_res=mysqli_query($con,$plan_sql);
while($row=mysqli_fetch_array($plan_res,MYSQL_BOTH))
{
?>
<option value="<?php echo $row['id'];?>"><?php echo $row['name'];?></option>
<?php
}
?>
</select>
</div>
<div class="form-group">
<label>Split 2</label>
<select class="form-control required" name='distance[]' id='distance' >
<option value="-1">Select Distance</option>
<?php
$plan_sql="select * from mytablename";
$plan_res=mysqli_query($con,$plan_sql);
while($row=mysqli_fetch_array($plan_res,MYSQL_BOTH))
{
?>
<option value="<?php echo $row['id'];?>"><?php echo $row['name'];?></option>
<?php
}
?>
</select>
</div>


enter image description here

Answer
<?php

// Run your query once and store the results

$plan_sql="select id, name from mytable";
$plan_res=mysqli_query($con,$plan_sql);
while ($row=mysqli_fetch_array($plan_res, MYSQL_BOTH)) {
    $result[] = $row;
};

// then you can add your selects without running the query repeatedly

for ($i=1; $i <= 20; $i++):?>
<div class="form-group">
    <label>Split <?php echo $i; ?></label>
    <select class="form-control required" name='distance[]' id='distance' >
        <option value="-1">Select Distance</option>
        <?php foreach ($result as $row): ?>
            <option value="<?php echo $row['id'];?>"><?php echo $row['name'];?></option>
        <?php endforeach ?>
    </select>
</div>
<?php endfor; ?>