Explode array values and insert into multiple SQL columns using PHP

Viewed 15

I'm working on a page where i expect users to enter datas in upto 10 different lines depending on their preference, take the question to be "What do you want for the month?" and the instruction is to start each in a new line. What i want to do is to insert each line in a seperate column with each row maintaining thesame value generated for the first column as in the sql table below.

Tablename

ID | PROFILEID  |   CHOICEID  | CHOICE
------------------------------------
1  | 1563187610 | GENERATED NO| FOOD
2  | SAME       | SAME        | IPHONE
3  | SAME       | SAME        | LAPTOP
4  | SAME       | SAME        | HOUSE
5  | SAME       | SAME        | LAND
------------------------------------

With all i have tried so far, it ends up inserting the query as one column.

The code i have tried

<?php

$profileid = $row['id'];
$choice_id = rand();
$choice = mysqli_real_escape_string($conn,$_POST["choice"]);
$choice = strip_tags($choice);
$choice = htmlspecialchars($choice);  

$choice_explode = explode("\n", str_replace(["\r\n","\n\r","\r"],"\n",$choice));

foreach ($choice_explode as $value) {

  // Attempt insert query execution
$sql = "INSERT INTO trades (profileid, choice_id, choice) VALUES ('$profileid', '$choice_id','.$value.')";
if(mysqli_query($conn, $sql)){
    echo "Records inserted successfully.";
} else{
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
 
// Close connection
mysqli_close($conn);
    
}?>
0 Answers
Related