dongruoqiong9017
dongruoqiong9017
2016-10-30 11:25
浏览 49
已采纳

如何在PHP中设置单选按钮的值?

How do I set names for each radio button in the following PHP code using counter variable, or any other alternative?

<?php  

        $id=0; //counter variable 

        $sql ="select roll_number,student_name,gender from student_table";
        $query=mysqli_query($dbcon, $sql) or die(mysqli_error($dbcon));

          while($post=mysqli_fetch_assoc($query)){

             echo '<tr>';
            echo '<td>'. $post['roll_number'] . '</td>';
            echo '<td>'. $post['student_name'] . '</td>';
            echo '<td>'. $post['gender'] . '</td>';
            echo '<td width=250>';

            echo '<input type="radio" name="rad'.$id'" value="P" />Present';
            echo '<input type="radio" name="rad'.$id'" value="A" />Absent';

            echo '<button type="submit" name="save" value="Save" class="btn btn-success btn-sm">Save</button>';
            ++$id;
            echo '</td>';
            echo '</tr>';               

            }

           ?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • duanliang9288
    duanliang9288 2016-10-30 11:48
    已采纳
    echo '<input type="radio" name="rad[' . $post['roll_number'] . ']" value="P" />Present';
    echo '<input type="radio" name="rad[' . $post['roll_number'] . ']" value="A" />Absent';
    

    On the receiving end you may do like this:

    $answers = $_POST['rad'];
    foreach($answers as $roll_number=>$answer){
        //do something with the $roll_number and $answer...
    }
    
    点赞 评论
  • dongzhi6146
    dongzhi6146 2016-10-30 11:59

    Updated the code, changed the $post to $row, concatenated the strings, fixed the <button> and so on. There is no form-declaration anywhere - if you have only one form, this will save / fetch every item in the form - depending on your needs, you might wanna declare a form per student, with a unique identifier.

    <?php  
    
    $query = mysqli_query($dbcon, 'SELECT roll_number,student_name,gender FROM student_table') or die(mysqli_error($dbcon));
    
    while ($row = mysqli_fetch_assoc($query)) {
    
        echo '<tr>
                <td>'.$row['roll_number'].'</td>
                <td>'.$row['student_name'].'</td>
                <td>'.$row['gender'].'</td>
                <td width="250">
                    <label><input type="radio" name="rad['.$row['roll_number'].']" value="P">Present</label>
                    <label><input type="radio" name="rad['.$row['roll_number'].']" value="A">Absent</label>
                    <input type="submit" name="save" value="Save" class="btn btn-success btn-sm">
                </td>
            </tr>';
    }
    
    ?>
    
    点赞 评论

相关推荐