GROUP_CONCAT inside an INSERT statement

281 views Asked by At

I am not really sure if this is possible, or if there is any alternative way to do this.

The following code takes multiple input from a user and inserts them in different rows, I don't want it like that. I am looking for a way to insert them in the same row.

<?php $test=$_POST['test'];

     foreach ($test as $a => $b){?>

            <?php echo $test[$a];?>
<?php    

  if( !$error ) {

   $query = "INSERT INTO test_tbl(test) VALUES('$test[$a]')";
   $output = mysql_query($query);

   if ($output) {
    $errTyp = "success";
    $errMSG = "Update Posted";
    ?>

I am aware there is a GROUP_CONCAT function but I can't seem to get it to work in insert statements and from researching I found out it doesn't really work with insert only with select. So is there any way of sorting this mess?

Here is my attempt on the GROUP_CONCAT (Obviously it's a big error that I receive)

$query = "INSERT INTO testing(item) VALUES(GROUP_CONCAT($test[$a]))";

PS I know this is completely against normalization standards but I am doing it since a customer requested it..

1

There are 1 answers

2
Rasso On BEST ANSWER

If i understood correctly you are inserting in a foreach loop, this will insert each $test[$a] seperately each time the loop runs. ALternatively you can put all $test[$a] values in an array and then insert that array in one row(which is way faster than multiple insert queries).

Here is a way to do it:

$all_test_values = array();
foreach ($test as $a => $b){

             $all_test_values[] = $test[$a];
}
$comma_separated = implode(",", $all_test_values);
if( !$error ) {

   $query = "INSERT INTO test_tbl(test) VALUES('$comma_separated')";
   $output = mysql_query($query);
}

PS: mysql is bad use mysqli instead