Jump to content
cjkeane

Retaining checkbox selections in a loop

Recommended Posts

Hi everyone,

I need to retain the checkbox selections after the form is submitted, but I'm stuck and wondering if anyone can offer some assistance?  Thank you.

<?php 
    $categories = mysqli_query($db,'SELECT id, category FROM category');
    if (!$categories) {
        exit('<p>Unable to obtain category list from the database.</p>');
    }
    // Check if there are any categories and if so, list them.
    if (mysqli_num_rows($categories) != 0){
        echo '<p>Select the related categories:<br />';
        while ($category = mysqli_fetch_array($categories)) {
            $categoryid = $category['id'];
            $categoryname = htmlspecialchars($category['category']);
            $checked= ($category['id']==$categories) ? ' checked="checked"' : '';
            echo '<input type="checkbox" name="categories[]" value="'.$categoryid.'" '.$checked.' > '.$categoryname.' <br/>';
        }
   }
?>

 

Share this post


Link to post
Share on other sites
Posted (edited)

Where is the code that handles the inputs, ie the checkbox selections,  that are being submitted?  That would be the place to worry about this question, so show us that code.

PS - I think this line is a problem

($category['id']==$categories) 

You are comparing a string var to a resource.  No can do.  If you had php error checking on you might be getting the message.

Edited by ginerjm

Share this post


Link to post
Share on other sites

Here is the full script.  The error reporting didn't help.

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    ob_start();                
    require_once('db.php');            
	require_once('auth.php');          
	require_once('functions.php');      
?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <title>Bookings</title>
        <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https:///resources/demos/style.css">
        <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
        <script>
            // This is a jquery datepicker function.  The dateFormat specifies that the date selected from the calendar will be in the yyyy-mm-dd format.
            $( function() {
                $('#date').datepicker({dateFormat: 'yy-mm-dd'});
            } );
        </script>       
         <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
        <link href="assets/css/styles.css" rel="stylesheet" >
    </head>
    <body>
        <div class="container">
            <div id="header">
                <figure><img src="logo.png"></figure>
                <?php 
                    $logged_on_name = "<span class='red-highlight'>" . ($_SESSION["SESS_NAME"]) . " </span>";
                    $usergroup = "<span class='red-highlight'>" . ($_SESSION["SESS_USERGROUP"]) . " </span>";
                    echo "<p>Welcome " . $logged_on_name . "</p>";
                ?>
            </div>
            <div style="clear:both"></div>
            <ul>
                <li><a href="admin_index.php">HOME</a></li>
                <li><a href="admin_customers.php">CUSTOMERS</a></li>
                <li><a class="active" href="admin_bookings.php">BOOKINGS</a></li>
                <li><a href="admin_categories.php">CATEGORIES</a></li>
                <li style="float:right"><a href="logout.php">LOGOUT</a></li>  
                <li style="float:right"><a href="admin_users.php">USERS</a></li>
            </ul>
            <div id="main" class="row">
                <?php 
                    // If the Add New User button is clicked, redirect to the admin_add_user.php page.
                    if(isset($_POST['AddNew'])){ 
                        $page ="admin_add_user.php";
                        header("Refresh: 0; url=$page"); 
                    }   
                ?>
                <h2>Bookings:</h2>
                <?php
                    $customerid = $_POST['customerid'];
                    $description = $_POST['description'];
                    $categories= $_POST['categories'];
                    $date= $_POST['date'];
                    if(isset($_POST['Save']) && !empty($_POST['Save'])) {
                        // Begin form validation
                        $error = false;
                        if (empty($customerid)) { $error = true; $customeridError = "Please select a customer name."; } 
                        if (empty($description)) { $error = true; $descriptionError = "Please type a booking description."; } 
                        if (empty($date)) { $error = true;  $dateError = "Please select a date."; } 
                        // end form validation and if there are no errors, insert new record with a hashed password
                        if (!$error) {
                            $sql = "INSERT INTO booking SET description='$description', date='$date', customerid='$customerid'";
                            if (mysqli_query($db,$sql)) {
                                echo '<p>New booking added</p>';
                            } else {
                                exit('<p>Error adding new booking</p>');
                            }
                            $bookingid = mysqli_insert_id($db); 
                            if (isset($_POST['categories'])) {
                                $categories = $_POST['categories'];
                            } else {
                                $categories = array();
                            }
                            $numcategories = 0;
                            foreach ($categories as $catID) {
                                $sql = "INSERT IGNORE INTO bookingcategory SET bookingid=$bookingid, categoryid=$catID";
                                $ok = mysqli_query($db,$sql);
                                if ($ok) {
                                    $numcategories = $numcategories + 1;
                                } else {
                                    echo "<p>Error inserting booking into category $catID: " . '</p>';
                                }
                            }
                            echo "<p>Booking was added to " . $numcategories . " categories.</p>";
                        } else {
                            echo '<div style="color: red; text-align: center;" >Save Failed. <i class="fa fa-thumbs-o-down" aria-hidden="true"></i> There are validation errors. Try again.  </div>';
                        }
                    } 
                ?>
                <?php
                    $customer = mysqli_query($db,'SELECT id, name FROM customer');
                    if (!$customer) {
                        exit('<p>Unable to obtain customer list from the database.</p>');
                    }
                    $categories = mysqli_query($db,'SELECT id, category FROM category');
                    if (!$categories) {
                        exit('<p>Unable to obtain category list from the database.</p>');
                    }
                ?>
                <form method="post" action="">
                    <input type="submit" class="btn" name="Save" type="submit" id="Save" value="Save">
                    <p>Enter the new booking:<br />
                    <textarea name="description" rows="5" cols="45" placeholder="Enter a booking description"><?php echo $description; ?></textarea></p>
                    <span class="text-danger" style="color:red; font-size:14px;"><?php echo $descriptionError; ?></span>
                    <p>Date<input type="text" id="date" name="date" value="<?php echo $date; ?>"></p>
                    <span class="text-danger" style="color:red; font-size:14px;"><?php echo $dateError; ?></span>
                    <p>Select customer name:</p>
                    <?php
                        // Create a query to retrieve the category list.
                        $result = mysqli_query($db,'SELECT id, name FROM customer');
                        $options = '';
                        while ($row = mysqli_fetch_array($result)) { 
                            // $selected makes sure that the selected value is retreived and set as selected.
                            $selected = ($row['id']==$customerid) ? ' selected="selected"' : '';
                            $options .= "<option value=\"{$row['id']}\"{$selected}>{$row['name']}</option>\n"; 
                        } 
                    ?>
                    <select name="customerid" id="customerid" >
                        <option value="" selected disabled hidden>Select one <?php echo $options ?></option>
                    </select>
                    <span class="text-danger" style="color:red; font-size:14px;"><?php echo $customeridError; ?></span>
                    <p>Place in categories:<br />
                        <?php
                            while ($category = mysqli_fetch_array($categories)) {
                                $categoryid = $category['id'];
                                $categoryname = htmlspecialchars($category['category']);
                                $checked= ($category['id']==$categories) ? ' checked="checked"' : '';
                                echo '<input type="checkbox" name="categories[]" value="'.$categoryid.'" '.$checked.' > '.$categoryname.' <br/>';
                            }
                        ?>
                    </p>
                    <span class="text-danger" style="color:red; font-size:14px;"><?php echo $categoriesError; ?></span>
                </form>
            </div>           
            <div id="copyright" class="row">
                <p><?php copyright(); ?></p>
            </div>
        </div>
    </body>
</html>
<?php 
    ob_end_flush();
?>

 

Share this post


Link to post
Share on other sites

A category would be checked if its id is in the array of category ids from the form input.

Share this post


Link to post
Share on other sites

Sorry can't help you.  Too much spaghetti code between your business logic and your presentation logic.  Shouldn't mix the two.

Share this post


Link to post
Share on other sites

This appears to be what you have now on submit:

$sql = "INSERT IGNORE INTO bookingcategory SET bookingid=$bookingid, categoryid=$catID";

So there are 2 things to note here:

  1. On a new booking a booking row gets created and you get the id of this new booking row and store it in $bookingid
  2. For each category selected a row is inserted in bookingcategory with the bookingid and the categoryid

So, the first issue you need to deal with is how will php get the bookingid that has just been created?  Your primary options are

  1. either to redirect to the same script, only passing a url parameter like ?bookingid=
  2. Set a cookie with the booking id there
  3. Use a session variable

I would suggest that you use sessions, since they have the advantage of hiding the bookingid from the user.  If you pass a parameter, anyone looking at your system could just change the booking id parameter and see other bookings, however, if this is an admin system, perhaps that doesn't matter as much.  Still sessions have great utility and may help with other problems you'll face.

Now assuming, you want to be able to add to this script, the logic you described, what is missing is that you need to SELECT the booking and related information so you can refill the form variables or otherwise display the booking data which has now been saved.  It should be obvious to you that you can't do that unless you have access to the saved booking id.

Getting a list of the preselected categories would require a query like:

SELECT c.* FROM bookingcategory bc
JOIN category c ON c.id = bc.categoryid
WHERE bc.bookingid = $bookingid

The actual query may be slightly different as there is no way to intuit the actual column names from your posted code.  The results of that query can be used to set the selected categories in your form/UI.

Share this post


Link to post
Share on other sites

Thanks for  all the responses.  I am close. I want to retain the check marks before the form is submitted.  I have this so far.  It retains the check marks, but it selects all check boxes right away. 

 <p>Select the categories:<br />
                        <?php
                        if (isset($_POST['categories'])) {$checked = 'checked'; } else { $checked = '';}
                            while ($category = mysqli_fetch_array($categories)) {
                                $categoryid = $category['id'];
                                $categoryname = htmlspecialchars($category['category']);
                                echo '<input type="checkbox" checked="'.$checked.'" name="categories[]" value="'.$categoryid.'" > '.$categoryname.' <br/>';
                            }
                        ?>
                    </p>

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.