简体   繁体   中英

Multiple INSERT INTO MySQL from $_POST array

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.

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

// 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";

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM