2

I am receiving the following arrays from a form:

array (size=1)
    'checkbox' => 
array (size=2)
    0 => string '14' (length=2)
    1 => string '13' (length=2)
    2 => string '15' (length=2)
array (size=1)
    'id' => string '1' (length=1)

I need to build a query looking like this:

$sql = "INSERT INTO table(column1,column2) VALUES (14,1),(13,1),(15,1)";
And the first array will be different every time based on the checked checkboxes.

2 Answers 2

3

Well, you can try looping with a foreach on that array. So let's say you have named your checkboxes as name="checkbox[]".

Then on the page where you are processing the $_POST vars you can do

$sql = "INSERT INTO table(column1,column2) VALUES (?,?)";
$stmt = $mysqli->prepare($sql);
foreach ($_POST['checkbox'] as $box) {
    //process each checkbox here
    $stmt->bind_param('ss', $box, $otherValue);
    $stmt->execute();
}

This is just a pseudo-code to get you started.

You can find more info on prepared statements here: http://php.net/manual/en/mysqli-stmt.bind-param.php

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

Comments

1
// Create an empty array to store each checkbox value
$values = array();

if(is_array($_POST['checkbox'])){
    foreach($_POST['checkbox'] as $checkbox){
        foreach($checkbox as $key => $value){

            // add each checkbox value to an array
            $values[] = ($value,$_POST['id']);

        }
    }
}

// if the array has values..
if(count($values)){

    // implode the values into a string..
    $sqlValues = implode(',',$values);

    // ..and use that string in the query
    $sql = "INSERT INTO table(column1,column2) VALUES $sqlValues";

}

1 Comment

This code is broken. It looks like you tried to use tuples in PHP and PHP doesn't have tuples. Besides this is not how you use prepared statements. The SQL would still be broken if you did it this way.

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.