0

I'm doing a cart system, when a client select various items the data is sent as string with IDs and comma as delimiter, example: 1,2,3

I save that to the database and I can show each item description using a custom function and foreach. The problem is if a client want to remove a item, how should I proceed to update the new changes to the DB? Because I tried with str_replace and I can only remove the ID but keeps the delimiter (comma), example: 1,2, or 1,,3

Any ideas or suggestions how can I improve this? Thank you for your time.

Regards.

  • 1
    Normalise your database. Don't store the cart list as a comma-separated list. Set up a table for it. It'll make querying, updating and reporting much easier. – Tangentially Perpendicular Apr 29 '21 at 23:04
  • 1
    Normalize the schema. See ["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) (Spoiler: Yes it is.). – sticky bit Apr 29 '21 at 23:08
  • You are right, I must normalize the schema. – thisisendz Apr 29 '21 at 23:13
  • Storing delimited lists in a DB is still bad, but if you otherwise needed to do this: https://www.php.net/manual/en/function.explode https://www.php.net/manual/en/function.implode – Sammitch Apr 29 '21 at 23:15

1 Answers1

-1

You should really normalise the schema, but...

There are many ways to do this. Here's one using using explode() and implode().

function removeIdFromString(string $str, string$id):string {
    $arr = explode(',',$str);
    if (($key = array_search($id, $arr)) !== false) {
      unset($arr[$key]);
      return implode(',',$arr);
    }
}    


$str = "3,5,7,9";
echo removeIdFromString($str,7);     // 3,5,9


echo removeIdFromString($str,9);     // 3,5,7

Good for PHP7+

Demo:https://3v4l.org/qBP9q