Stian Berg Larsen
Stian Berg Larsen

Reputation: 553

HTML Form - Send each row as array

So, I guess this might be a simple question, but I cant really get my head around it at the moment... =S

I have a form, that gets data from my database.

It contains one column of names, and then two columns with checkboxes.

When I submit this form, I want to update the database with the given checkboxes.

So, the form is loaded and filled with for example 5 different names/users. Each user has 2 checkbox selections. (3 columns in total).

As it is now, it works for all except when only the last of the two checkboxes are checked. Then my code sees it as only the first checkbox is checked.. (because the unchecked checkbox is not sent, so my last checkbox is then in the array position of my first checkbox).

Sorry for my very bad explanation. I hope you get what my problem is.

Here is some code:

<form id="rsvpRegForm" method="post" action="updateRSVP.php">
                    <h2>Kryss av for kirke og/eller middag:</h2>
                    <br>
                    <table id="rsvpRegTable" border="0">
                    <?php while($guest = $guestSQL->fetch_assoc()){ ?>
                        <tr>
                            <td style="text-align:left" width="200px"><?=$guest['guestName']?><input type="hidden" name="guest<?=$guest['guestID']?>[]" value="<?=$guest['guestID']?>"></td>
                            <td><input type="checkbox" <?php if(isset($guest['guestChurch'])){if($guest['guestChurch'] == 1){ echo 'checked';}} ?> value="1" name="guest<?=$guest['guestID']?>[]">Kirke</td>
                            <td><input type="checkbox" <?php if(isset($guest['guestParty'])){if($guest['guestParty'] == 1){ echo 'checked';}} ?> value="1" name="guest<?=$guest['guestID']?>[]">Middag</td>
                        </tr>
                    <?php } ?>

                    </table>
                    <br>
                    <input type="submit" value="Send RSVP">
                </form>

And this is the code responsible for updating my database with the results:

foreach($_POST as $guest){  

if(!isset($guest[1])){
    $guest[1] = 0;
}

if(!isset($guest[2])){
    $guest[2] = 0;
}

$stmt = $mysqli->prepare('UPDATE rsvp_guests SET 
    guestReplied = ?,
    guestChurch = ?,
    guestParty = ?
    WHERE guestID = ?');


$stmt->bind_param('dddd',
    $rsvpReplied,
    $guest[1],
    $guest[2],
    $guest[0]);

$stmt->execute();
$stmt->close();
}

Upvotes: 0

Views: 159

Answers (1)

Wrikken
Wrikken

Reputation: 70460

Name the something like name="guest<?=$guest['guestID']?>[party]" & name="guest<?=$guest['guestID']?>[church]", so you know which one is on or off.

Upvotes: 1

Related Questions