简体   繁体   中英

insert multiple values into multiple rows with prepared statement PHP, MYSQL

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

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.

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