Forum Moderators: coopster
Dependent on a numeric variable $size, posted via a radio button on the preceding page, a list of buttons is generated from a MySQL table, which, at present, consists of 5 columns - size, drive1, drive2, drive3, and drive4. The values in the size column are numbers relating to the radio buttons on the previous page. The values in the drive columns are text - such as "electric" "gearbox" and so on.
Columns size and drive1 will always have a value. The others may not.
So far, I have come up with this code:
$query = "SELECT drive1,drive2,drive3,drive4 FROM $drivestable WHERE size = $size";
$result = mysql_query($query) or die ("Error in query: $query. " .
mysql_error());
echo '<div class=nobullets>'; // strips bullets from list
echo '<form action="nextpage.php" method="post">';
while ($row = mysql_fetch_row($result)) {
foreach ($row as $item) {
if ($item == "") {
echo ""; // stops listing where there is no value in a drive column in $drivestable
}
else {
echo '<li>';
echo '<p><input type="radio" name="drive" value= "' . $item . '">' . $item.'</p>';
echo '</li>';}
}
}
echo '<p><input type="submit" name="Submit" value="Continue"> to see widget size ranges available with a' . $size .' thingamy and selected drive</p>';
echo '</form>';
echo '</div>';
This generates the radio buttons beautifully - but I would be grateful for adivce on how to have the first button always checked. That seems preferrable to having an error check which would cause another page to be loaded.
said that see the comments: //
while ($row = mysql_fetch_row($result))
{
$i = 0; // init $i before foreach
foreach ($row as $item)
{
$checked = ++$i == 1? ' checked' : ''; // if first radio check it, else, not check it
...
echo '<p><input type="radio" name="drive"';
echo 'value= "'.$item.'"'.$checked.'>'; // put $checked
echo $item.'</p>';
...
comment please...
---
I have not seen that very neat way of writing an if / else statement before, either. I've much to learn.
However, I am still not getting the first button checked. To try and find why, I added an extra line of code - as follows:
echo '<p><input type="radio" name="drive"';
echo 'value= "'.$item.'" '.$checked.'>'; // put $checked
echo $item.'</p>';
echo $checked;
This showed the word "checked" came up where expected, after the first button.
So at the moment, I cannot see why the first button is not checked - I'd be grateful for any further thoughts.
I agree that often it is better to leave radio buttons unchecked - but in this particular case, I think it is acceptable.