0

I'm trying to insert data from a multiselect into a database with multiple rows.

I once managed to insert them all into ONE row, each with a comma which is not really good from the database perspective. The data from the multiselect is stored as an array in a variable, which then should be filled into multiple rows in the database with a foreach loop.

$array = implode((array)$_POST['multiselectdata']);

$sql = "INSERT INTO tbl_example (column1, column2) VALUES (?, ?)";

$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
    ....
    exit();
}
else {
    mysqli_stmt_bind_param($stmt, "ii", $array, $id);
    mysqli_stmt_execute($stmt);
    $result= mysqli_stmt_store_result($stmt);
    mysqli_fetch_all($result,MYSQLI_ASSOC);
    foreach($result as $row){
        echo $row["column1"];
    }
    exit()
}

As a result in each row there should be 1 value displayed of the array in column1 and in column2 there is always going to be the same id. Currently this only inserts 1 value into the database and only 1 row

2
  • If you want to insert multiple rows, why do you execute that query only once? Commented May 7, 2019 at 12:34
  • mysqli_stmt_execute($stmt); should be in the foreach loop that was my fault. Topic is answered perfectly below by Nick. This can be done with a foreach loop with an array or either with explode if the values are all available seperated with a comma. Commented May 7, 2019 at 12:42

1 Answer 1

2

Rather than implode the contents of $_POST['multiselectdata'] you can iterate over it as an array and execute your prepared statement for each value in the array:

$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
    // ....
    exit();
}
else {
    mysqli_stmt_bind_param($stmt, "ii", $value, $id);
    foreach (explode(',', $_POST['multiselectdata']) as $value) {
        mysqli_stmt_execute($stmt);
    }
}

Note that calling mysqli_stmt_store_result on an INSERT query makes no sense as there is no result set. That line and the foreach loop following should be removed from your code.

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

3 Comments

Thank you very much for your answer. Unfortunately it is not quite working yet. The data in $_POST['multiselectdata'] is stored like this: 1,2,3,6. Do I need to mention the "," for the foreach loop to work properly?
@RobinP sorry I thought from your code that $_POST['multiselectdata'] was an array. In that case you will to explode it. See my edit.
thank you very much for your help! I also got confused first, because I initially thought it would be an array. It works fine now

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.