0

I am working on a system whereby a user is given a choice of 7 checkboxes - each representing a day of the week.

If they tick M,T,W,T,F then I insert 12345 into the database as a string - if they choose W,T,F,S,S I insert 34567 into the database and so on. The insert is all working fine.

When I then retrieve the data from the database I am struggling to show them which days they currently have chosen. I have taken the data from the database and exploded it into individual items and then have a foreach loop but I am not sure what to do with it next:

$wdays_array = str_split($wdays);

foreach($wdays_array as $day) {
 // do something here
}

Further down I then have HTML code which I use to insert in the first place which I need to change to checked if the value is set when they come back to modify their choices:

<ul>
 <li><input type="checkbox" name="wdays[]" value="1"/> <label>Monday</label></li>
 <li><input type="checkbox" name="wdays[]" value="2"/> <label>Tuesday</label></li>
 <li><input type="checkbox" name="wdays[]" value="3"/> <label>Wednesday</label></li>
 <li><input type="checkbox" name="wdays[]" value="4"/> <label>Thursday</label></li>
 <li><input type="checkbox" name="wdays[]" value="5"/> <label>Friday</label></li>
 <li><input type="checkbox" name="wdays[]" value="6"/> <label>Saturday</label></li>
 <li><input type="checkbox" name="wdays[]" value="7"/> <label>Sunday</label></li>
</ul>

How do I ensure the correct checkboxes are checked when the user reloads the form based on what is currently in the field in MySQL?

Thanks

1 Answer 1

1

plenty of ways to do this, I would try

<ul>
 <li><input type="checkbox" name="wdays[]" value="1"<?php if(in_array(1, $wdays_array)){echo "checked='checked'";}?>/> <label>Monday</label></li>
 <li><input type="checkbox" name="wdays[]" value="2"<?php if(in_array(2, $wdays_array)){echo "checked='checked'";}?>/> <label>Tuesday</label></li>
 <li><input type="checkbox" name="wdays[]" value="3"<?php if(in_array(3, $wdays_array)){echo "checked='checked'";}?>/> <label>Wednesday</label></li>
....
</ul>

check out in_array

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.