PHP/MySQL: How to save or insert the selected radi

2019-09-22 05:17发布

问题:

I have a table having n rows. Each row has a name [came from an Excel file] and 2 sets of radio buttons. How should I save or insert the selected radio buttons in a database?

The structure of my database is: id, name, vote_for_mayor, vote_for_vmayor

Here's my php code.

echo '<form name="electionForm" action="submit.php" method="post" onreset="updateButCount(event);">
<button type="submit" value="Submit">Submit</button>

<table id="election" onclick="updateButCount(event);">
list($cols,) = $xlsx->dimension();
$var=0;
$var1=0;
foreach( $xlsx->rows() as $k => $r) {
    $var++;
    $var1++;
    <tr>
        <td>'.$k.'</td>
        <td>'.( (isset($r[0])) ? $r[0] : '&nbsp;' ).'</td>  //names
        <td><input type = "Radio" Name ="vote'.$var.'" value= "pacada"></td>
        <td><input type = "Radio" Name ="vote'.$var.'" value= "toledo"></td>
        <td><input type = "Radio" Name ="vote1'.$var1.'" value= "apostol"></td>
        <td><input type = "Radio" Name ="vote1'.$var1.'" value= "abdul"></td>
    </tr>
}
</table>
</form>';

回答1:

Change the HTML to:

    <td><input type = "Radio" Name ="vote['.$var.']" value= "pacada"></td>
    <td><input type = "Radio" Name ="vote['.$var.']" value= "toledo"></td>
    <td><input type = "Radio" Name ="vote1['.$var.']" value= "apostol"></td>
    <td><input type = "Radio" Name ="vote1['.$var.']" value= "abdul"></td>

Then when processing the form, the variables $_POST['vote'] and $_POST['vote1'] will be arrays containing the value of the radio button on each row. You can loop through them and insert them into the database.