jarvis Posted August 31, 2009 Share Posted August 31, 2009 Hi all, Happy Bank holiday! Rather embarassingly, I've never had to use checkboxes on my forms and now I need to. How do I store and retrieve checkbox values using php & mysql? Any sample code would be most helpful!!! Thanks in advanced! Quote Link to comment https://forums.phpfreaks.com/topic/172544-phpmysql-store-and-retrieve-checkbox-values/ Share on other sites More sharing options...
Alex Posted August 31, 2009 Share Posted August 31, 2009 You can store 1 for a checked box and 0 for an unchecked box. So.. Inserting: $checkbox = (isset($_POST['some-check-box'])) ? 1 : 0; //Insert $checkbox into mysql.. Getting back from the database: //Query etc... $checkbox = ($row['checkbox'] == 0) ? NULL : 'checked="checked"'; echo "<input type='checkbox' name='whatever' $checkbox />"; Quote Link to comment https://forums.phpfreaks.com/topic/172544-phpmysql-store-and-retrieve-checkbox-values/#findComment-909558 Share on other sites More sharing options...
jarvis Posted August 31, 2009 Author Share Posted August 31, 2009 Thanks alexWD but what if it's for multiple options? Like a menu for example? Quote Link to comment https://forums.phpfreaks.com/topic/172544-phpmysql-store-and-retrieve-checkbox-values/#findComment-909584 Share on other sites More sharing options...
Alex Posted August 31, 2009 Share Posted August 31, 2009 For that it's a bit different, you'd store the selected value and do something like this: Storing: $selected = mysql_real_escape_string($_POST['select-menu']); //Query Then for displaying it with the selected one: //Query.. $items = Array('Menu Option 1', 'Menu Option 2', 'Menu Option 3'); foreach($items as $item) { $menu .= ($row['selected'] == $item) ? "<option value='$item' selected='selected'>$item</option>" : "<option value='$item'>$item</option>"; } Then $menu would contain the contents of the <select..></select>. Quote Link to comment https://forums.phpfreaks.com/topic/172544-phpmysql-store-and-retrieve-checkbox-values/#findComment-909586 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.