问题
What I want to do is have a radio button inside a while loop and the name of the radio to be increased by 1 every time the loop is ran.
Right now the code is not working because it is not incrementally increasing. Any suggestions would be great.
$query = mysql_query("SELECT * FROM table WHERE id = '1' ORDER BY time ASC");
echo '<table> <th> A </th> <th> time </th> <th> B </th>';
while($row = mysql_fetch_assoc($query)) {
$i= 1;
echo '<tr><td>';
echo '<input type="radio" name="';echo $i++; echo'" /> '; echo $row['a'];
echo '</td>';
echo '<td>';
echo $row['time'];
echo '</td>';
echo '<td>';
echo '<input type="radio" name="';echo $i++; echo '" />'; echo $row['b'];
echo '</td> </tr> ';
}
echo '</tr></table>';
回答1:
You're resetting your counter each time.
$i = 1;
while($row = mysql_fetch_assoc($query)) {
// Your code
$i++;
}
.. and replace echo $i++;
with echo $i;
.
回答2:
just move the $i= 1;
outside the loop
like this for instance:
...
$i= 1;
while($row = mysql_fetch_assoc($query)) {
...
echo '<input type="radio" name="';echo $i; echo'" /> '; echo $row['a'];
...
...
$i++;
}
回答3:
your logic is not valid:
$i = 0;
while($row = mysql_fetch_assoc($query)) {
$i++;
echo '<tr><td>';
echo '<input type="radio" name="';echo $i; echo'" /> '; echo $row['a'];
echo '</td>';
echo '<td>';
echo $row['time'];
echo '</td>';
echo '<td>';
echo '<input type="radio" name="';echo $i; echo '" />'; echo $row['b'];
echo '</td> </tr> ';
}
every time you type $i++
PHP will increment it.
回答4:
Hehe.. ;))
$query = mysql_query("SELECT * FROM table WHERE id = 1 ORDER BY time ASC");
echo "<table>\n";
echo " <tr>\n";
echo " <th> A </th>\n";
echo " <th> time </th>\n";
echo " <th> B </th>\n";
echo " </tr>\n";
$i = 0;
while($row = mysql_fetch_assoc($query)) {
echo " <tr>\n"
echo ' <td><input type="radio" name="' . $i . '" />' . $row['a'] . "</td>\n";
echo ' <td>' . $row['time'] . "</td>\n";
echo ' <td><input type="radio" name="' . $i . '" />' . $row['b'] . "</td>\n";
echo " </tr>\n";
$i++;
}
echo "</table>\n";
I didn't check your code including the SQL query if it's right, yet do the rest to fix this code if there's an error or if the format wasn't right!
来源:https://stackoverflow.com/questions/15748840/php-while-loop-with-i