Bill Flippen
Bill Flippen

Reputation: 453

mysqli update from an array

I am stuck on whether the first step is this the right way and how to proceed to the next step.

on page 1 I have:

$query="select  index_member, name from members where active=1 order by name";
$rs=$db->query($query);`

I then fill a table with radio dials

while($row = $rs->fetch_assoc()) {
    if ($column == 0) {
        echo "<tr>";
    }   

    echo "<td>".$row['name']."</td><td align='center'>";
    echo "<input type='radio' name=".$row['index_member']." value='0'></td>";
    echo "<td align='center'><input type='radio' name=".$row['index_member']." '";
    echo "value='1' checked></td> ";

    $column++;

    if ($column >= 2) {
        echo "</tr>";
        $column=0;
    }
}

this shows:

name1 0 1

name2 0 1

name3 0 1

(the 0 and 1 represent the values for the radio button)

and then post to a 2nd page. Doing a print_r($_POST); on the second page returns:

Array ( 
    [21] => 0 
    [7] => 1 
    [12] => 0 
    [20] => 1 
    [33] => 0 
    [22] => 1......

I want to cycle through update members set active = *value* where member= *key*;

I am unsure how to extract the array info and insert it into the variables of the query.

Additionally, are there any special considerations for mysqli?

Upvotes: 2

Views: 2159

Answers (1)

Kevin
Kevin

Reputation: 41885

I suggest name them this way:

echo '<td>';
echo '<input type="radio" name="member['.$row['index_member'].']" value="0" />';
echo '<input type="radio" name="member['.$row['index_member'].']" value="1" checked />';
echo '</td>';

Then, just treat it like a normal $_POST.

The indices are the index_member, the pair value are the values:

$members = $_POST['member'];

$sql = 'UPDATE members SET active = ? WHERE index_member = ?';
$update = $db->prepare($sql);
foreach($members as $index_member => $val) {
    $update->bind_param('ii', $val, $index_member);
    $update->execute();
}    

Upvotes: 2

Related Questions