checkbox to mysql blues
Page 1 of 2 12 LastLast
Results 1 to 15 of 21

Thread: checkbox to mysql blues

  1. #1
    Member
    Join Date
    Jan 2012
    Posts
    47

    checkbox to mysql blues

    Okay, I've a small issue with a database project. I'm creating a database using php from an html form. the database works but I have a checkbok that users can check using the html form. The other fields word but the check box does not. Here is the code to see what I'm doing wrong.

    PHP Code:
    <input name="survey" type="checkbox" id="survey" value="yes" <?php echo ($_POST['survey'] == 'yes' 'checked' '');?> />
    phpmyadmin says it 0 whether i checked or not. i'm using a tinyint(1) as my data type. Thanks in advanced!

  2. #2
    Pna lbh ernq guvf¿
    Join Date
    Jul 2004
    Location
    Kansas City area
    Posts
    19,432
    The code you've shown us isn't really relevant (other than to show us the name/value of the checkbox form entity, I suppose).

    What we need to see is the PHP code that processes form submissions and inserts/updates data in the DB.

  3. #3
    Member
    Join Date
    Jan 2012
    Posts
    47

    the code

    PHP Code:
    if (isset($_POST['submitted'])){
        
    $fields = array(
        'email',
        'state',
        'district',
        'gender',
        'age',
        'profession',

    );

    foreach($fields as $fieldName) {
        if(isset($_POST[$fieldName]) and trim($_POST[$fieldName]) !==''){
            $$fieldName = trim($_POST[$fieldName]);
        }else {
            
                    $errors[] = "Please enter your". $fieldName .""; //code to validate fields
        }
    }
    if(!isset($errors)){
        
    require_once('Connections/encourage.php');

    $query = "INSERT INTO participants (email, state, district, gender, age, profession, survey, registration_date) 
    VALUES ('$email', '$state', '$district', '$gender', '$age', '$profession','$survey', NOW())"; //databasse connection
       
        $result = mysql_query ($query);     

    if ($result){
        
        echo '<h1 id="mainhead">Thanks for submitting</hl>
        <p>You are now registered</p>';
        exit();
        
        }else{
        
        echo '<h1 id="mainhead">System Error</hl>
        <p>Your registration could not be completed due to a system error We apologize for any incovience</p>';//gives system error
        echo 'p' . mysql_error(). '<br /><br />Query: ' . $query . '</p>';
        exit();
        
        }
        mysql_close();
        
        } else { 
            
            echo '<h1 id="mainhead">Error!</h1>
            <p class="error">The following error(s) occurred:<br />';
            foreach($errors as $msg) {
                echo " - $msg<br/>\n";
            }
            echo '</p><p>Please try again.</p><p><br/></p>';
        }

    }
    ?>
      <form id="form1" name="form1" method="post" action"registration.php">
      <fieldset class="first">
      <label class="lableone" for="email">Email:* </label>
      <input name="email" value="<?php if(isset($_POST['email'])) echo $_POST['name'];?>"/>
      
      <label for="state"/>State:* </label>
      <input name="state" value="<?php if(isset($_POST['state'])) echo $_POST['state'];?>"/>
      
      <label for="schooldistrict"/>School District:* </label>
      <input name="district" value="<?php if(isset($_POST['district'])) echo $_POST['district'];?>" />
      
      <label for="gender">Gender:* </label>
     <select name="gender">
       <option>Choose Your Gender</option>
       <option value="male" <?php echo ($form['gender'] == 'male' ' selected' ''); ?>>Male</option>
       <option value="female"<?php echo ($form['gender'] == 'female' ' selected' ''); ?>>Female</option>
     </select>
      
        <label for="age"/>Your Age:* </label>
      <input name="age" type="text" class="age" maxlength="2" value="<?php if(isset($_POST['age'])) echo $_POST['age'];?>"  />
      
      <label for="profession"/>Profession:* </label>
      <input name="profession" value="<?php if(isset($_POST['profession'])) echo $_POST['profession'];?>" />
      
      <label for="survey"/>Willingness to participate in future surveys: </label>
      <input name="survey" type="checkbox" id="survey" value="yes" <?php echo ($_POST['survey'] == 'yes' 'checked = "checked"' '');?> />
      
      </fieldset>
    <fieldset>
      <input class="btn" name="submit" type="submit" value="Submit" />
    <input class="btn" name="reset" type="reset" value="Clear Form" />
    <input type="hidden" name="submitted" value="TRUE" />
    </fieldset>

      </form>

  4. #4
    Pna lbh ernq guvf¿
    Join Date
    Jul 2004
    Location
    Kansas City area
    Posts
    19,432
    And where do you convert the string "yes" (which is the value of the checkbox when checked) to a numeric value that would fit in a tinyint(1) column?

    EDIT: In addition, where do you define the variable $survey ?

  5. #5
    Member
    Join Date
    Jan 2012
    Posts
    47

    the objective

    That I do not know. I'm using tinyint(1) for a reason, my phpmyadmin at 1and1 does not support Boolean . I'm using mysql version 5.0. If i'm using tinyint, Since its coming zeros anyways, I would like to read "0" for no "1" for yes. It would be great if the database records when the user click the check box = "yes", not checked ="no"

    I can prob use boolean for true or false but i'm open to suggestions, advice, and the correct php syntax. Thanks

  6. #6
    Senior Member traq's Avatar
    Join Date
    Jun 2011
    Location
    so.Cal
    Posts
    949
    BOOLEAN is the same thing (i.e., an alias) for TINYINT.

    One solution would be to change your inputs to use value="1" rather than value="yes".

    The other would be to translate any 'yes' values into 1 values before putting them into the query.

    HOWEVER--

    Your code is open to SQL injection. Your "validation" function makes sure that fields are not empty, but does not sanitize them. You need to be using mysql_real_escape_string() to prevent problems.

    Also, what happens when the survey box is not checked? Your $survey variable would not be set. You should be getting a warning about that when you try to use it even though it doesn't exist.

  7. #7
    Pna lbh ernq guvf¿
    Join Date
    Jul 2004
    Location
    Kansas City area
    Posts
    19,432
    Quote Originally Posted by traq
    BOOLEAN is the same thing (i.e., an alias) for TINYINT.
    That's true in the latest version of MySQL, yes, but I still prefer using 'BOOL' (or 'BOOLEAN') when applicable since a) you never know if that might change in the future, and b) I find 'BOOL' to be more descriptive/transparent than 'TINYINT(1)'.

    @cybereclipse: Also note that '1' is different than 1. Taking that into consideration, plus traq's observations above regarding security as well as the issue of a possibly undefined variable, one suggestion I might make would be to do something like:

    PHP Code:
    $survey = isset($_POST['survey']) ? 0
    which is a) compact, and b) takes care of both sanitization and undefined variable errors.

  8. #8
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,910
    Quote Originally Posted by traq
    Your code is open to SQL injection. Your "validation" function makes sure that fields are not empty, but does not sanitize them. You need to be using mysql_real_escape_string() to prevent problems.
    Of course, for a checkbox this is easily done because its value is not as important as whether it's even there in the submitted data or not because that is what indicates whether or not it was checked (if it is present, insert 1; if it's not, insert 0).

    Not to say that it's just as important to make sure all the other fields are sanitised. And it may also be a good idea to start moving away from the long-term deprecated MySQL extension (and perhaps into one with parameterised queries that do the necessary escaping automatically).
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  9. #9
    Senior Member traq's Avatar
    Join Date
    Jun 2011
    Location
    so.Cal
    Posts
    949
    Quote Originally Posted by bradgrafelman View Post
    ... I still prefer using 'BOOL' (or 'BOOLEAN') when applicable since a) you never know if that might change in the future, and b) I find 'BOOL' to be more descriptive/transparent than 'TINYINT(1)'.
    agreed.

    Quote Originally Posted by bradgrafelman View Post
    @cybereclipse: Also note that '1' is different than 1...
    In my experience, both 1 and '1' are evaluated (in BOOL columns) as 1 by mysql.
    ...tested just now on 5.1.14

    I've never thought about it before, and after a quick search I couldn't find documentation to indicate if this is intentional (and/or reliable). Do you know of an answer? Specifically, if this might be unreliable across versions or configurations?

  10. #10
    Pna lbh ernq guvf¿
    Join Date
    Jul 2004
    Location
    Kansas City area
    Posts
    19,432
    Quote Originally Posted by traq View Post
    Do you know of an answer?
    Not really... I suppose it's more of a personal preference than anything else. MySQL, just like PHP, does know when to do some automatic type juggling when you give it something that doesn't make sense (e.g. give it a string of ASCII characters rather than numeric values). I blame it on my C/C++ background.

  11. #11
    Member
    Join Date
    Jan 2012
    Posts
    47

    okay

    Yes, awesome. I'm very aware that I need to secure my code but that's my next step. Not to familiar with that so could anyone help me out with that?

  12. #12
    Senior Member
    Join Date
    Mar 2009
    Posts
    813
    Quote Originally Posted by cybereclipse View Post
    Yes, awesome. I'm very aware that I need to secure my code but that's my next step. Not to familiar with that so could anyone help me out with that?
    String data should be put through the mysql_real_escape_string() function and data that you're expecting to be an integer should be cast as an integer.
    Declare variables, not war.

  13. #13
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,910
    Quote Originally Posted by cybereclipse
    I'm very aware that I need to secure my code but that's my next step.
    Security is not just something you can bolt on afterwards. It's something you have to keep in mind right from the start.

    "Yes, I know anyone can just open the car door, get in, start it and drive away. Adding security is my next step."
    Last edited by Weedpacket; 03-25-2012 at 01:16 AM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  14. #14
    Senior Member
    Join Date
    Aug 2008
    Location
    London, UK
    Posts
    753
    I'd probably go with an enum data type for the field for this. It's a yes/no value so it's unlikely to change unless you need that mysterious third value of 'maybe'. Internally it's stored as a tinyint, so there's no extra storage used (IIRC) and you use it in your queries as if it were a string, so it would work perfectly in the above code where it's being compared to the value of 'yes'
    Ashley Sheridan
    www.ashleysheridan.co.uk

  15. #15
    Member
    Join Date
    Jan 2012
    Posts
    47

    Hey Ashley

    Thanks for your response. I will try enum but I have a question, If I use that data type, would this code work


    PHP Code:
     <input name="survey" type="checkbox" value="<?php echo (isset($_POST['survey']))? 'checked' 'unchecked';?>" />

    ||

    PHP Code:
    $survey = isset($_POST['survey']) ? 0
    that bradgrafelman provided?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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