1

OK, so this is the last hurdle in the development side of my uni project, which is due VERY soon, I need to pick my daughter up from school in a minute (so I apologise for any delay in response - I assure you that I have not disappeared).

OK, so I am displaying various times (booking slots) to users which have been retrieved from the database. The user can then select the radio button relating the the time slot they wish to book. I have appended a counter so that the radio buttons each have a unique id. Upon clicking the 'book appointment' button the startTime value and slotId values need to be inserted into the bookings table, along with the bookingId from the availability table and userId from the users table, based on the current SESSION.

My problem is that as the radio buttons have different values, I am unsure how to define which radio button has been selected, and therefore how to write the query in which to insert the data relating to each unique radio button.

I know there is going to be an if statement in there somewhere, I am just not sure how to approach it, I have spent ages mulling this over, I am running out of time, the dog is driving me insane and my daughter means that time is very limited, so I really do appreciate any help or guidance offered :)

bookings.php `

        }
            ?>

<!--Display available slots based on chosen date-->
<?php
        if(isset($_POST['getDate'])){
            $datepicker = strip_tags($_POST['datepicker']);
            $datepicker = $DBcon->real_escape_string($datepicker);

            $sql=("SELECT slotId, startTime, endTime, date FROM availability 
WHERE date= '".$datepicker."'");
            $query_s=mysqli_query($DBcon, $sql);
            $row=mysqli_fetch_array($query_s);
            if (!$row) {echo 'Error, No bookings available for this date, 
please choose another';}

            $counter = 1;
            while ($row=mysqli_fetch_array($query_s)){
                $id = 'slot_id'.$counter;
                $counter++;

                //echo '<div class="col-lg-3 col-md-3 col-sm-4 col-xs-6">';
            ?>
                <table class="table-responsive">
                <form class="form-bookings" method="post" action="<?php echo 
htmlspecialchars($_SERVER['PHP_SELF']); ?>" autocomplete="off">                    
<tbody>
                    <tr>
                        <td><?php echo $row['startTime'] ?></td>
                        <td><?php echo $row ['endTime'] ?></td>
                        <td><input type="radio" name="<?php echo ['slotId']?
>" id="<?php $id ?>" Value="<?php echo ['startTime']?>"></td>
                        <td><?php echo $id ?></td>
                    </tr>
                    </tbody>
<?php
             }                        
        }
 ?>
        </form>
     </table>
    </div>
</div>
</div>`


Bookings Table columns are:
`bookingId
slotId
userId
startTime`
Anniee
  • 73
  • 6
  • 1
    The HTML code you are creating is a mess. table can not be a child of table, and neither can form be a child of table. Plus, you are opening a form inside the loop, but the only closing form tag is after the loop ... If this works at all, then rather by accident. And what your actual question/problem is, is rather unclear. – CBroe May 15 '17 at 13:36
  • OK, not sure where `` came from. As for the form element, I did not know that it cannot be a child of a table. Is form before table the correct way? My problem is that I do not know how to insert the name, and id's of the radio boxes into the bookings table when they are selected by the user.
    – Anniee May 15 '17 at 13:46
  • *"I am unsure how to define which radio button has been selected"* - You would use `isset()` and a POST array pulled from a named attribute for them and its value. – Funk Forty Niner May 15 '17 at 14:05
  • Yes I have began with `if(isset($_POST['bookApp'])){}` and I would POST the `slotId` and `startTime` yes? Could you give me an example of this please as I am unsure of how to do it. – Anniee May 15 '17 at 14:53

1 Answers1

1

Last edit (09.06.2017):

<?php
/*
 * Some general recommendations:
 * 
 *  - Always provide semicolons (;) in PHP codes.
 *  - Maintain lowercase for the HTML attributes.
 *  - Start/end HTML tags on the same page scope. Same for PHP codes.
 *  - Don't write text direct in body. Wrap it in span, div, label, etc, first.
 *  - The HTML tags should also have a coressponding end/close tag.
 *    Only the ones that requires it (div, span, etc).
 *    Breaks, inputs, etc don't require this
 *  - Always validate $_GET, $_POST, $_SESSION, etc, values
 *    and assign defaults if not valid.
 *  - Use camelCase when naming PHP variables.
 *  - Preserve table structure definition. Inject HTML tags only where they belong.
 *    When using forms (<form>) with tables (<table>), insert them just in TD's (<td>),
 *    not anywhere else. Or wrap the whole table in a form.
 */

// Code for session starting and includes...
?>
<!DOCTYPE HTML>
<html>
    <head>
        <title>App/page title</title>
    </head>
    <body>
        <?php
        try {
            //-------------------------------------------------------
            // Read the user ID from session.
            //-------------------------------------------------------
            $userId = isset($_SESSION['userId']) ? $_SESSION['userId'] : NULL;

            /*
             * -----------------------------------
             * Upon submission by book app button.
             * -----------------------------------
             */

            $bookApp = isset($_POST['bookApp']) ? $_POST['bookApp'] : NULL;

            if (isset($bookApp)) {
                $bookingMessages = '';

                // Get posted availabilityId.
                $receivedAvailabilityId = isset($_POST['availability']) ? $_POST['availability'] : NULL;

                // Insert availability_id & user_id into bookings
                if (isset($receivedAvailabilityId)) {
                    /*
                     * -------------------------------------------
                     * Insert the booking information into the DB.
                     * -------------------------------------------
                     */

                    $sqlBookAvailability = "INSERT INTO bookings (availability_id, user_id) VALUES (" . $receivedAvailabilityId . ", " . $userId . ")";

                    $isAvailabilityBooked = mysqli_query($DBcon, $sqlBookAvailability);

                    if (!$isAvailabilityBooked) {
                        throw new Exception('The selected availability could not be booked.');
                    }

                    // Get last inserted booking ID upon booking.
                    $lastInsertedBookingId = mysqli_insert_id($DBcon);

                    if ($lastInsertedBookingId == 0) {
                        throw new Exception('The selected availability could not be booked.');
                    }

                    $bookingMessages .= "The selected availability were successfully booked. Booking ID: " . $lastInsertedBookingId . ".";
                    $bookingMessages .= "<br/>";
                } else {
                    $bookingMessages .= "Please choose an availability.";
                    $bookingMessages .= "<br/>";
                }

                echo $bookingMessages;
            }

            /*
             * ----------------------------------------
             * Upon selection of a date in date picker.
             * ----------------------------------------
             */

            // Read selected date from date picker.
            $getDate = isset($_POST['getDate']) ? $_POST['getDate'] : NULL;

            if (isset($getDate)) {
                $postDatePicker = isset($_POST['datepicker']) ? $_POST['datepicker'] : NULL;
                $strippedDatePicker = strip_tags($postDatePicker);
                $datePicker = mysqli_real_escape_string($DBcon, $strippedDatePicker);

                /*
                 * ---------------------------------
                 * Display available availabilities.
                 * ---------------------------------
                 */

                $sqlBookedAvailabilities = "SELECT av.id, av.start_time, av.end_time, av.date 
                                            FROM availabilities as av 
                                            LEFT JOIN bookings AS bo ON bo.availability_id = av.id 
                                            WHERE bo.id IS NULL AND av.date = '" . $datePicker . "'";

                $queryBookedAvailabilities = mysqli_query($DBcon, $sqlBookedAvailabilities);

                if (!$queryBookedAvailabilities || mysqli_num_rows($queryBookedAvailabilities) == 0) {
                    echo 'No bookings available for this date, please choose another.';
                    echo '<br/>';
                } else {
                    ?>
                    <form id="chooseAvailabilities" class="form-bookings" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post" autocomplete="off">
                        <table class="table-responsive">
                            <tbody>
                                <?php
                                // Read availabilities list.
                                while ($rowAvailability = mysqli_fetch_array($queryBookedAvailabilities)) {
                                    $availabilityId = $rowAvailability['id'];
                                    $availabilityStartTime = $rowAvailability['start_time'];
                                    $availabilityEndTime = $rowAvailability ['end_time'];
                                    ?>
                                    <tr>
                                        <td>
                                            <?php echo $availabilityStartTime; ?>
                                        </td>
                                        <td>
                                            <?php echo $availabilityEndTime; ?>
                                        </td>
                                        <td>
                                            <input type="radio" name="availability" id="availability_id<?php echo $availabilityId; ?>" value="<?php echo $availabilityId; ?>">
                                        </td>
                                        <td>
                                            &nbsp;
                                        </td>
                                    </tr>
                                    <?php
                                } // End reading availabilities list.
                                ?>
                                <tr class="book-appointment-outer-wrapper">
                                    <td colspan="4" class="book-appointment-inner-wrapper">
                                        <button type="submit" class="btn btn-default" name="bookApp">
                                            Book Appointment
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </form>
                    <?php
                }
            } // End reading date from date picker.

            $closed = mysqli_close($DBcon);
            if (!$closed) {
                echo 'The database connection can not be closed!';
            }
        } catch (Exception $exception) {
            echo $exception->getMessage();
            exit();
        }
        ?>
    </body>
</html>
  • Thank you so much for all of the information, I have only had time to have a quick look at the moment, I will look at this properly later on and mark as answer etc :) – Anniee May 16 '17 at 16:04
  • You're welcome! You need a lot of time for it, so no hurry. Please mark an answer only if it provides you the real solution to your problem. Or at least the main principles which inevitable guide you in finding your own right solution(s). Feel free to ask anything. P.S: I didn't presented you the DB-related code, having in mind that you already used similar, proper DB-acces codes in your page. Essentially, I tried to present you the usual way of handling the radio button context and the posting and receiving of corresponding data. –  May 16 '17 at 16:25
  • It really is very helpful, thank you! I am trying to get my head around it all now. When you write `: NULL;` are you assigning the default value as NULL, yes? Also, would I be heading in the right direction if I wrote the following... `// Get startTime from "availability" table on the basis of $receivedSlotId value. $startTime = ("SELECT startTime from availability where slotId= '" . $receivedSlotId . "'");` – Anniee May 16 '17 at 18:35
  • Yes, I give NULL as default value. Good point! But I made this with a precise purpose: maintaining a general coding standard in your code. This way you assure a general validation and "assigning-of-default-values" form. Think of such statements as beeing found only in a function, which can be later called where needed. I know it's a reassigning of NULL to a variable, which already had NULL as value ;-) –  May 16 '17 at 18:54
  • That form with `?` and `:` is a shorthand if-else statement. See this short answer: [ANSWER](http://stackoverflow.com/questions/1506527/how-do-i-use-shorthand-if-else). Very easy explained. –  May 16 '17 at 19:03
  • Yes, the `SELECT` statement for `$startTime` is perfect. –  May 16 '17 at 19:06
  • Maybe is easier for you to separate my whole comments from the actual php page content, in order to have a better view of the actual code. –  May 16 '17 at 19:10
  • I have looked into the short-hand if-else, and I understand, thanks. I also understand what you are saying, about assigning NULL to a variable for later use, I will do my best to implement it :) I'm not sure what is wrong with my query though, its outputting NULL for `$receivedSlotId`! If I dump the query I get `"SELECT startTime from availability where slotId= ''"` – Anniee May 16 '17 at 20:27
  • I found the problem. Somehow strangely my last edit on answer had no effect. I just rechanged it by passing the right value and posted as my new edited answer. It should be "slot" instead "slotId". Exactly like this: `$receivedSlotId = isset($_POST['slot']) ? $_POST['slot'] : NULL;` –  May 16 '17 at 21:21
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/144396/discussion-between-anniee-and-aendeerei). – Anniee May 16 '17 at 21:28
  • Hello, I have only just seen this - sorry. Thank you for asking, I am struggling with a few things, have tried to chat with you. – Anniee May 24 '17 at 10:25
  • @Anniee Hi, Anniee. I updated my answer with the last code version. Remember to accept it, if it works for you. Have a nice day. –  Jun 09 '17 at 06:24
  • @Anniee Hi. I'm online. I need you as soon as possible in chat. –  Jun 18 '17 at 16:12