0

I've a problem that confuses me and can not get solved...

I have 1 for each loop which runs through all products and then inside I have another for each loop for some specific product parameters that I need to combine into one string (string, array or serialized data) and save info in data base.

foreach ($products as $product) {
    $parameter1 = $product_parameter1;
    foreach ($products_extra_parameters as $product_extra_parameter) {
        $parameter2 .= $product_extra_parameter . '|';
    }
$insert_data = "INSERT INTO table (parameter1,parameter2) values ('$parameter1','$parameter1')";
if (!mysqli_query($conn, $insert_data)):
    fwrite($fh, "Error: " . $insert_data . "\n" . mysqli_error($conn). "\n");
endif;
}

The problem is that with '.=' it adds previous results to the next product (first product have: 'product1_parameter2_value1|product1_parameter2_value' and next one: 'product1_parameter2_value1|product1_parameter2_value|'product2_parameter2_value1|product2_parameter2_value' and so on and on...

I just need to save combined product attributes in 1 table column (using just string combining or can be serialize) for appropriate product and just this product parameters! And I'll have several such parameters that I need to combine in 1 parameter and save in 1 column...

What I'm missing here/doing wrong?

Mole_LR
  • 69
  • 1
  • 10
  • 1
    simply set `$parameter2` to an empty string just before the second `foreach` – Patrick Q Oct 11 '17 at 21:14
  • 2
    [Is storing a delimited list in a database column really that bad?](https://stackoverflow.com/questions/3653462/is-storing-a-delimited-list-in-a-database-column-really-that-bad) – Don't Panic Oct 11 '17 at 21:17
  • daaa...TNX! That's it! Stupid mistake... – Mole_LR Oct 11 '17 at 21:17
  • 2
    @Mole_LR I suggest you check out Don't Panic's link above because you should not be storing your attributes in this way. – Mike Oct 11 '17 at 21:18
  • @Mike! For this specific "needs" comma (or whatever) separated list is quite enough, in normal scenarios of course not! I think I even will use serialize data... – Mole_LR Oct 11 '17 at 21:21
  • It always works until it doesn't. ;) Just food for thought, anyway. You know your application better than us random internet people. – Don't Panic Oct 11 '17 at 21:22
  • why not just use [implode](http://php.net/manual/en/function.implode.php)? `$parameter2 = implode('|',$products_extra_parameters);` – Tony Chiboucas Oct 11 '17 at 21:41

0 Answers0