I have received so much help from this site and the amazing people on it. I am humbled by the amount of knowledge everyone here has. I am hoping that you can help me with something that I am struggling to figure out. I have a check box that successfully writes to my db but I can only get it to work with 1 and 0. I would like checked = yes unchecked to = no but I cant figure it out. Here is the code I am currently using.

<strong>Active: *</strong> <input type="checkbox" name="Active" value="1" <?php if($Active == 1) echo 'checked="checked"'; ?>"/><br/>

and

$Active = (int)$_POST['Active'];

    I haven't seen your other code, but at the point you are inserting into your database, you need to insert "yes" if $POST["Active"] is 1 or "no" otherwise. Note that if your checkbox is not checked when you submit, then $POST["Active"] will not even be defined.

      In other words...

      $Active = !empty($_POST['Active']) ? 'yes' : 'no';
      

        Here is the full code. I can get it to write 1 or 0 but I cannot figure out how to make it write yes or no. I tried following the example found here

        http://www.html-form-guide.com/php-form/php-form-checkbox.html

        but I no idea where it is suppose to go in the code or how it is suppose to be formatted.

        <?php
                /*
                    Allows the user to both create new records and edit existing records
                */
        
            // connect to the database
            include("connect-db.php");
            error_reporting(E_ALL);
            ini_set('display_errors', 1);
            // creates the new/edit record form
            // since this form is used multiple times in this file, I have made it a function that is easily reusable
            function renderForm($first = '', $middle = '', $last = '', $ClientID = '', $Diagnosis = '', $Gender = '', $LevelCare = '', $Counselor = '', $Active = '', $aftercare = '', $error = '', $id = '')
            { ?>
                <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
                <html>
                    <head>  
                        <title>
                            <?php if ($id != '') { echo "Edit Record"; } else { echo "New Record"; } ?>
                        </title>
                        <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
                    </head>
                    <body>
                        <h1><?php if ($id != '') { echo "Edit Record"; } else { echo "New Record"; } ?></h1>
                        <?php if ($error != '') {
                            echo "<div style='padding:4px; border:1px solid red; color:red'>" . $error
                                . "</div>";
                        } ?>
        
                        <form action="" method="post">
                        <div>
                            <?php if ($id != '') { ?>
                                <input type="hidden" name="id" value="<?php echo $id; ?>" />
                                <p>id: <?php echo $id; ?></p>
                            <?php } ?>
        
                            <strong>First Name: *</strong> <input type="text" name="FirstName"
                                value="<?php echo $first; ?>"/>
        						<strong>Middle Name: </strong> <input type="text" name="MiddleName"
                                value="<?php echo $middle; ?>"/>
        						<strong>Last Name: *</strong> <input type="text" name="LastName"
                                value="<?php echo $last; ?>"/><br/>
        						<br/>
                                <strong>Client ID: *</strong> <input type="text" name="ClientID"
                                value="<?php echo $ClientID; ?>"/>
        						<strong>Diagnosis: *</strong> <input type="text" name="Diagnosis"
                                value="<?php echo $Diagnosis; ?>"/>
        					    <strong>Gender: *</strong> <input type="text" name="Gender"
                                value="<?php echo $Gender; ?>"/><br/>
        						<br/>
                                <strong>Level of Care: *</strong> <input type="text" name="LevelCare"
                                value="<?php echo $LevelCare; ?>"/>
                                <strong>Counselor: *</strong> <input type="text" name="Counselor"
                                value="<?php echo $Counselor; ?>"/><br/>
        						<br/>
        						<strong>Active: *</strong> <input type="checkbox" name="Active" value="1" <?php if($Active == 1) echo 'checked="checked"'; ?>"/><br/>
        						<br/>
        						<strong>Active: *</strong> <input type="checkbox" name="aftercare" value="1" <?php if($aftercare == 1) echo 'checked="checked"'; ?>"/><br/>
                            <p>* required</p>
                            <input type="submit" name="submit" value="Submit" />
                        </div>
                        </form>
                    </body>
                </html>
        
            <?php }
        
        
        
                /*
        
                   EDIT RECORD
        
                */
            // if the 'id' variable is set in the URL, we know that we need to edit a record
            if (isset($_GET['id']))
            {
                // if the form's submit button is clicked, we need to process the form
                if (isset($_POST['submit']))
                {
                    // make sure the 'id' in the URL is valid
                    if (is_numeric($_POST['id']))
                    {
                        // get variables from the URL/form
                        $id = $_POST['id'];
                        $FirstName = htmlentities($_POST['FirstName'], ENT_QUOTES);
                        $MiddleName = htmlentities($_POST['MiddleName'], ENT_QUOTES);
                        $LastName = htmlentities($_POST['LastName'], ENT_QUOTES);
                        $ClientID = htmlentities($_POST['ClientID'], ENT_QUOTES);
                        $Diagnosis = htmlentities($_POST['Diagnosis'], ENT_QUOTES);
                        $Gender = htmlentities($_POST['Gender'], ENT_QUOTES);
                        $LevelCare = htmlentities($_POST['LevelCare'], ENT_QUOTES);
                        $Counselor = htmlentities($_POST['Counselor'], ENT_QUOTES);
        	    $Active = (int)$_POST['Active'];
                    $aftercare = (int)$_POST['aftercare'];
        
                        // check that FirstName, LastName and ClientID are not empty
                        if ($FirstName == '' || $LastName == '' || $ClientID == '' || $Diagnosis == '' || $Gender == '' || $LevelCare == '' || $Counselor == '')
                        {
                            // if they are empty, show an error message and display the form
                            $error = 'ERROR: Please fill in all required fields!';
                            renderForm($FirstName, $MiddleName, $LastName, $ClientID, $Diagnosis, $Gender, $LevelCare, $Counselor, $Active, $aftercare, $error, $id);
                        }
                        else
                        {
                            // if everything is fine, update the record in the database
                            if ($stmt = $mysqli->prepare("UPDATE clients SET FirstName = ?, MiddleName = ?, LastName = ?, ClientID = ?, Diagnosis = ?, Gender = ?, LevelCare = ?, Counselor = ? , Active = ?, aftercare = ? WHERE id=?"))
                            {
                                $stmt->bind_param("ssssssssssi", $FirstName, $MiddleName, $LastName, $ClientID, $Diagnosis, $Gender, $LevelCare, $Counselor, $Active, $aftercare, $id);
                            	$stmt->execute();
                           	 	$stmt->close();
                            }
                            // show an error message if the query has an error
                            else
                            {
                                echo "ERROR: could not prepare SQL statement.";
                            }
        
                            // redirect the user once the form is updated
                            header("Location: view-paginated.php");
                        }
                    }
                    // if the 'id' variable is not valid, show an error message
                    else
                    {
                        echo "Error!";
                    }
                }
                // if the form hasn't been submitted yet, get the info from the database and show the form
                else
                {
                    // make sure the 'id' value is valid
                    if (is_numeric($_GET['id']) && $_GET['id'] > 0)
                    {
                        // get 'id' from URL
                        $id = $_GET['id'];
        
                        // get the record from the database
                        if($stmt = $mysqli->prepare("SELECT ID, FirstName, MiddleName, LastName, ClientID, Diagnosis, Gender, LevelCare, Counselor, Active, aftercare FROM clients WHERE id=?"))
                        {
                            $stmt->bind_param("i", $id);
                            $stmt->execute();
        
                            $stmt->bind_result($id, $FirstName, $MiddleName, $LastName, $ClientID, $Diagnosis, $Gender, $LevelCare, $Counselor, $Active, $aftercare);
                            $stmt->fetch();
        
                            // show the form
                            renderForm($FirstName, $MiddleName, $LastName, $ClientID, $Diagnosis, $Gender, $LevelCare, $Counselor, $Active, $aftercare, NULL, $id);
        
                            $stmt->close();
                        }
                        // show an error if the query has an error
                        else
                        {
                            echo "Error: could not prepare SQL statement";
                        }
                    }
                    // if the 'id' value is not valid, redirect the user back to the view.php page
                    else
                    {
                        header("Location: view.php");
                    }
                }
            }
        
            // close the mysqli connection
            $mysqli->close();
        ?>

          Oh come on! NogDog pretty much handed you the answer. You should at least try and understand your own code. You seem to know which line to change:

          $Active = (int)$_POST['Active'];
            sneakyimp;11045407 wrote:

            Oh come on! NogDog pretty much handed you the answer. You should at least try and understand your own code. You seem to know which line to change:

            $Active = (int)$_POST['Active'];

            I apologize, I misunderstood. there was a reply about not seeing my other code, so I posted it. Please feel free to delete that post if possible.

              NogDog thank you so much for the help. I am most grateful. I have only been doing this stuff about 2 weeks and I having straightforward answers like your really makes a difference. I salute you. I have a few other questions that I am sure are very simple if you would be willing to chat with me about them.

                NogDog one question. When I check the checkbox it writes to the database, but when I go back to the form the checkbox is no longer checked. Is there a way to make sure the box retains its selected state?

                  Depends on how you "go back to the form". If you do a HTTP redirect, then you'll need to set the desired status in a session variable that you can check within the form display code. If you just include() the form template from the same script that processed the request, you could just look at what you have in that variable.

                  Basically, it could be something like:

                  <input type="checkbox" name="foo"<?php if(!empty($_POST['foo'])) { echo ' checked="checked"'; }?> />
                  

                  Or you could use that ternary operator again:

                  <input type="checkbox" name="foo"<?php echo !empty($_POST['foo']) ? ' checked="checked"' : ''; }?> />
                  

                    Unfortunately, you can't just check if it's empty in this case because the value from the db will be either YES or NO rather than defined/empty.

                      I decided to go a little more user friendly route and changed the code to this

                      <label><input type="checkbox" name="Active[]" value="1" <?php if($Active == 1) echo 'checked="checked"'; ?>"/>Yes</label>
                              <label><input type="checkbox" name="Active[]" value="0" <?php if($Active == 0) echo 'checked="checked"'; ?>"/>No</label>

                      For some reason no is always checked.

                      I have an index page which shows a form if I click edit record it takes me to the edit page where this code is located. on submit it returns me to the index. Whenever I click on edit record with the old code from above nothing was checked. No as I said no is always checked. I tried your suggestion above and failed miserable. I wish there was an easy way for me to learn this stuff, at 45 I am way past my prime lol.

                        Well, checkboxes wouldn't be an appropriate form element to use any more in that case; radio buttons should be used instead.

                          Thank you I will replace them with radio buttons

                            scampbell70;11045461 wrote:

                            I decided to go a little more user friendly route and changed the code to this

                            <label><input type="checkbox" name="Active[]" value="1" <?php if($Active == 1) echo 'checked="checked"'; ?>"/>Yes</label>
                                    <label><input type="checkbox" name="Active[]" value="0" <?php if($Active == 0) echo 'checked="checked"'; ?>"/>No</label>

                            For some reason no is always checked.

                            I have an index page which shows a form if I click edit record it takes me to the edit page where this code is located. on submit it returns me to the index. Whenever I click on edit record with the old code from above nothing was checked. No as I said no is always checked. I tried your suggestion above and failed miserable. I wish there was an easy way for me to learn this stuff, at 45 I am way past my prime lol.

                            If you are calling a record up from the database and using it to show this form, then $Active might be the string "yes" and not an integer 1 or a string "1". In that case, the test $Active==1 will always fail. Unfortunately, your form submission sends either a 1 or 0 when you submit a POST operation and this must be converted to "yes" or "no" for insertion into your database. Similarly, the db record's "yes" or "no" must be converted back to whatever can get the checkbox checked. The annoying part is that the values you get from POST are totally different from the values you get from the db.

                              I went with the radio buttons and they work great. I gave up on trying to get the other to work once buttons were suggested. Everyones help and insight is greatly appreciated.

                                Write a Reply...