I have checkboxes generated with this code:
while($row = $result->fetch_assoc()) {
echo "<input type='checkbox' name='branch[]' value='".$row['id']."'> ".$row['name']."<br>";
}
And I need to insert value of every checkbox in mysql database. Code that I have inserts it for every checkbox but only $member_id, $branch is always inserted as 0. What am I doing wrong?
$sql = "SELECT id FROM members WHERE email='$email'";
$result = mysqli_query($mysqli,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$member_id = $row["id"];
$checked_arr = $_POST['branch'];
$branch_count = count($checked_arr);
for ($i = 0; $i < $branch_count; $i++) {
if ($insert_stmt_branch = $mysqli->prepare("INSERT INTO members_branch (member, branch) VALUES (?, ?)")){
$insert_stmt_branch->bind_param('ss', $member_id, $branch);
if (! $insert_stmt_branch->execute()) {
echo "ERROR: branch insert";
}
}
}
$member_idand$branch.var_dump($row)$branchin$insert_stmt_branch->bind_param('ss', $member_id, $branch);does not exist. You want to use$checked_arr[$i]->$insert_stmt_branch->bind_param('ss', $member_id, $checked_arr[$i]);prepareyour SQL outside the loop, so you can reuse it.