0

I have a data array which is separated by a comma in database.

enter image description here now, what i want to do is implode the strings from the column purpose.

enter image description here

and make that checkbox lists in my form echo checked; if the list is in the database.

hope you guys can help me out. Thank You!

8
  • 1
    Please stop storing CSVs in columns. This is not how they are meant to be used. 1 value per column. Commented Jul 2, 2018 at 2:32
  • 2
    Please, show us, what have you tried to solve the problem. Otherwise we won't help. Commented Jul 2, 2018 at 2:35
  • 2
    Your database design is bad. You need to create a child table for storing purpose fields. Commented Jul 2, 2018 at 2:37
  • 1
    Possible duplicate of Is storing a delimited list in a database column really that bad? Commented Jul 2, 2018 at 2:37
  • okay i will edit it and post my code. Commented Jul 2, 2018 at 2:44

2 Answers 2

1

Here's an example (Not the proper way to design your code though) .

$purposesFull=array('a','b','c','d','e');
$purposesFromDB='a,b,d';
$purposesFromDBArray=explode(',',$purposesFromDB);
foreach($purposesFull as $item){
    $checked = in_array($item,$purposesFromDBArray) ? ' checked' : '';
    echo '<input type="checkbox" name="purs[]"'.$checked.'>'.$item;
    echo '<br/>';
}
Sign up to request clarification or add additional context in comments.

2 Comments

Your code has the correct output. i will try it first, based on my database.
Thank you very much. you really got the correct answer. You picture out what the kind of output i want to display. without showing my code.
1

If you must do this, then:

$checkedPurposes = preg_split('/\s*,\s*/', $purposeColumnFromDatabase);
// then for each checkbox
if (in_array($purposeName, $checkedPurposes)) {
    // echo checked
}

The regex ensures that typos regarding the number of spaces around the commas don't matter.

As other users have said in the comments though, this is bad database design. If you can change the schema to move the purposes into their own table, you probably should.

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.