0

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";
        }
    }
}
3
  • check the fetched array from where you are getting the values of $member_id and $branch. var_dump($row) Commented Dec 5, 2014 at 18:23
  • 1
    $branch in $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]); Commented Dec 5, 2014 at 18:23
  • 1
    You probably should prepare your SQL outside the loop, so you can reuse it. Commented Dec 5, 2014 at 18:23

2 Answers 2

1

At the start of your for loop, you forgot to add:

$branch = $checked_arr[$i];

Also, you don't have anything to verify that your query looking up by email address returns a value. If no account is found, your $member_id value will be blank.

Sign up to request clarification or add additional context in comments.

Comments

1

You never assign a value to $branch

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.