I received an input from a textarea in this format:
value0
value1
value2
value3
Now i want to explode this into an array, and implode back to string so that
INSERT INTO `table` (`valueField`, `myField`) VALUES
('value0','assignedValue'),
('value1','assignedValue'),
('value2','assignedValue'),
('value2','assignedValue')
Where assignedValue is fixed.
Here is what I did:
$myArray = explode(PHP_EOL, $_POST['input']);
foreach ($myArray as $key => $value) {
$myArray[$key] = trim(preg_replace('/\s\s+/', ' ', $value));
}
$data = "('" . implode("','assignedValue'),'", $myArray) . "'";
$sql = "INSERT INTO `table` (`valueField`, `myField`) VALUES $data";
echo $sql;
As the result, which is wrong:
INSERT INTO `table` (`valueField`, `myField`) VALUES ('value0','assignedValue'),'value1','assignedValue'),'value2','assignedValue'),'value3'
Also if there is a better way to do this in regex please.