curiosity
curiosity

Reputation: 844

implode a data from database to echo checkbox as checked

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!

Upvotes: 0

Views: 400

Answers (2)

Ashraf
Ashraf

Reputation: 2632

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/>';
}

Upvotes: 1

Erayd
Erayd

Reputation: 168

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.

Upvotes: 1

Related Questions