0

I have a table for clients that stores some basic info but in one row it also stores an array that looks something like this i.e. "1-1, 2-1, 3-1, 6-1, 7-1, 16-1, 17-1, 18-1"

the commas separate the "options", the number before the dash is the "option" ID, and the number after after the dash is the "option's" "quantity". each client might have different "options" with different "quantities"

I have this so far but I have no idea where to go from here.

<?php
        $out = "";
        $id_client ="";
        $id_client = $_SESSION['client_cod_card'];
        $sql="SELECT * FROM customer WHERE client_cod_card='$id_client'";
  $result = mysql_query ($sql);
  while ($row = mysql_fetch_array($result)){

      $in = $row['options'];
      $out = str_replace(',', '<br />', $in);

      echo $out;} ?>

and it gives me this

1-1
2-1
3-1
6-1
7-1
16-1
17-1
18-1

is there any way to echo that string into something like:

$option_id - $option_quantity
$option_id - $option_quantity
$option_id - $option_quantity
$option_id - $option_quantity
..

so I can use those numbers and get each option's info from another table and adjust the quantity.

I hope I managed to explain this somewhat understandable and I hope someone can give me a hand as this is the most frustrating thing I've gotten myself into. Thank you all in advance!

4
  • 3
    It's not a good idea to store comma-separated values in databases. It makes search and updating very difficult. Commented Sep 8, 2016 at 0:29
  • though I completely agree with Barmar (who couldn't?), this might help: php.net/manual/en/function.serialize.php Commented Sep 8, 2016 at 0:31
  • @Barmar your solution is perfect! I know I've bitten more than I can chew with this project but getting stuck is the only way to learn new things in this domain :)) Thank You! Commented Sep 8, 2016 at 1:09
  • @Jeff Serialize output can contain NULL bytes, notably when encoding private object properties, and MySQL does not play well with unescaped NULL bytes. I would suggest json_encode() instead, but once again storing serialized data like OP wants to is a super bad idea in the first place. Commented Sep 8, 2016 at 1:25

1 Answer 1

1

You can use explode() to split up the value into its parts. First split the whole list on the commas, then split each option on the hyphens.

$option_array = explode(',', $row['options'];
foreach ($option_array as $opt) {
    list($option_id, $option_quantity) = explode('-', $opt);
    // Use $option_id and $option_quantity here
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.