How can I make in PHP dropdown menu which will have options from 0 to certain number which mysqlquery will retrieve?
I've tried while loop but it just retrieves one option with value of mysql. iex. in mysql table there is value six (6). So I want it to printed like this:
<select name="count">
<option value="">Count</option>
<option value="1">1</option>
<option value="2">2</option>
.
.
.
<option value="6">6</option>
</select>
So far its this:
$count = mysql_query('SELECT count FROM table') or die ('MySQL error! Error with query!');
print('<select name="count">');
print('<option="">Count</option>');
while($values = mysql_fetch_array($count))
{
print('<option value="');
print $values;
print('">');
print $values;
print('</option>');
}
print('</select>');
Retrieve the number from your database - let us say it is stored in $maxnum
- then run through all the values from 1
to $maxnum
, using a for
loop, echoing an <option>
element in each loop iteration.
<select name="mynolist" id="mynolist" onchange="form.submit()">
<option value="">Select</option>
<?php
for($i = 0; $i <10; $i++)
{
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
?>
</select>
do it.
Here's how to do it. First, you need to get the results of the MySQL query into a variable (see the $result
line below). Then, you need to fetch the first row (since you are only returning a single row) into an array. Take the first element of that array to be your count value, then do a for loop against that to create the additional option
elements.
<select name="count">
<option value="">Count</option>
<?php
$result = mysql_query('SELECT count(*) FROM table') or die ('MySQL error! Error with query!');
$row = mysql_fetch_row($result);
$count = $row[0];
for($i=0; $i < $count; $i++)
{ ?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php } ?>
</select>