1

this is my code:

foreach ($_POST['id_serv'] as $key => $count) {
    $p_warna = $_POST['p_warna'.$count];
    $p_data = $p_warna;
    echo $p_data; 
    // if i set "echo" at this, i get value ("RedGreen") 
}   echo $p_data;
    // if i set "echo" at this, i get value ("Green") 

the quetion is how to make value $p_data to be like this: ("Red,Green"); if can do that, i can input them to database just one time for one column data.

thanks for your help before..

bayu666
  • 23
  • 8
  • 1
    Fill them in an array; and use `implode()` function to get a comma separated string – Madhur Bhaiya Oct 28 '18 at 18:02
  • @bayu666 One thing I just want to highlight, if you're taking this from the user input (and since it's the post array, you are) you'll want to insert it into the database using prepared statements and binding--otherwise you're an easy target for sql injection. – Ray Oct 28 '18 at 18:29
  • See this question for basics on protection against SQL injection in PHP: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Ray Oct 28 '18 at 18:31

1 Answers1

1

As mentioned in comment, add to an array and implode to create a concatenated string separated by whatever delimiter you want.

$a=array();

foreach ($_POST['id_serv'] as $key => $count) {
    $p_warna = $_POST['p_warna'.$count];
    $a[] = $p_warna;
    // if i set "echo" at this, i get value ("RedGreen") 
}  

echo implode(',', $a);
Ray
  • 40,256
  • 21
  • 101
  • 138
  • 1
    `array_push()` is overkill here. I would rather use `$a[] = $p_warna`. – Madhur Bhaiya Oct 28 '18 at 18:21
  • 1
    From [Docs](http://php.net/manual/en/function.array-push.php): If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function. – Madhur Bhaiya Oct 28 '18 at 18:23