将循环内的无线电值插入数据库PHP

时间:2017-05-15 13:32:01

标签: php mysql

好的,所以这是我的uni项目开发方面的最后一个障碍,很快就会到期,我需要在一分钟内从学校接我的女儿(所以我为任何延迟回应道歉 - 我保证你我还没有消失。)

好的,我正在向从数据库中检索到的用户显示不同的时间(预订位置)。然后,用户可以选择与他们希望预订的时隙相关的单选按钮。我添加了一个计数器,以便每个单选按钮都有一个唯一的ID。点击“预约”按钮后,startTime值和slotId值需要插入bookings表格,以及bookingId中的availability来自userId表的表格和users,基于当前的SESSION

我的问题是,由于单选按钮具有不同的值,我不确定如何定义选择了哪个单选按钮,因此如何编写查询以插入与每个唯一单选按钮相关的数据。

我知道那里会有一个if语句,我只是不确定如何接近它,我已经花了很多时间考虑这个,我已经没时间了,狗让我疯了,我的女儿意味着时间非常有限,所以我真的很感激提供的任何帮助或指导:)

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`

1 个答案:

答案 0 :(得分:1)

上次编辑(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>