SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Apr 2002
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Retrieving and Populating Checkboxes from MySQL

    I currently have a form that inserts the data into a MySQL db. I also have a form that will allow users to update their information. I am having trouble retrieving and populating the checkboxes from the database.

    I have 3 checkboxes: Energy, Economy, and Housing

    Information is stored in the db field "Interests"

    How can I get the fields to show checked if they had previously checked the information and also the ability to update their selections.

    Thanks!

  2. #2
    SitePoint Wizard siteguru's Avatar
    Join Date
    Oct 2002
    Location
    Scotland
    Posts
    3,629
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Assuming the data from the database is made available into variables (e.g. $economy) and these variables have true/false states ...

    Code PHP:
    <input type="checkbox" name="economy" value="yes" <?php if ($economy) echo 'checked="checked"' ?> >
    ... will pre-check the checkbox if true.

    How to get the data into the variables? Depends on exactly how the data is stored in the database.

    Note: to allow changes - please note that a checkbox form element is ONLY sent when the form is submitted IF IT IS CHECKED. An unchecked checkbox does not appear in the form collection, therefore you need to explicitly test for the checkbox ...

    PHP Code:
    if (isset ($_POST['economy']) {
      
    // Checkbox "economy" was checked

    Ian Anderson
    www.siteguru.co.uk

  3. #3
    SitePoint Enthusiast
    Join Date
    Apr 2002
    Posts
    25
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I use an array to put the checked fields into the field "Interests". Each value is seperated by a comma: Energy, Economy, Housing

  4. #4
    SitePoint Guru
    Join Date
    Jan 2007
    Posts
    967
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Nitestarz View Post
    I use an array to put the checked fields into the field "Interests". Each value is separated by a comma: Energy, Economy, Housing
    You can try something like this to parse the values into an array:

    Code PHP:
    $raw_data="Energy, Economy, Housing";
    $interests=explode(',',$raw_data);
     
    foreach ($interests as $v){
     
       $checked[$v]=" checked='CHECKED' ";
     
    }

    Implimentation:

    <input type=ckeckbox id="Energy" name="Energy" <?=$checked['Energy'] ?> ...


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •