简体   繁体   English

使用数据库中的值检查变量值

[英]Check variable values with values in a database

I have been trying to work this out for 2 days now without success.我已经尝试解决这个问题 2 天了,但没有成功。 I am trying to check form input values against existing values in a column called 'date' in the 'bookings' table in the database.我正在尝试根据数据库中“预订”表中名为“日期”的列中的现有值检查表单输入值。 If any matches are found, then the whole result needs to be false so that the query wont run.如果找到任何匹配项,则整个结果必须为假,这样查询才不会运行。

My code is such a mess of attempts, but I'm now showing the only idea that half worked.我的代码是一堆乱七八糟的尝试,但我现在展示的是唯一成功了一半的想法。 A user chooses a date or a date range.用户选择日期或日期范围。 These dates are checked against what exists in the 'date' column in the database.这些日期会根据数据库中“日期”列中存在的内容进行检查。 If any of the dates exist, the whole thing needs to be false, if none of the dates are found, it must be true and then those values can be saved to the database.如果存在任何日期,则整个事情需要为假,如果没有找到任何日期,则必须为真,然后可以将这些值保存到数据库中。 Here is what I have:这是我所拥有的:

    $sql = "
SELECT date
FROM bookings
;";

$result = $conn->query($sql);
$alreadyBooked = array();

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $alreadyBooked[] = $row['date'];
    } // while
} //  num rows


if(isset($_POST['submit'])){

$name = $_POST['name'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$arrive = strtotime($_POST['arrive']);
$depart = (strtotime($_POST['depart'])) - 86400;
?>

<p>You have chosen the following dates: </p>
 <a name="booking-form"></a> 

<?php



for ( $i = $arrive; $i <= $depart; $i = $i + 86400 ) {
        echo $bookedDates = date('Y-m-d', $i );


        if (in_array($bookedDates, $alreadyBooked)){
            $bookdedDatesNice = date('D, j M Y', strtotime($bookedDates));
            echo 'This date is not available : '.$bookdedDatesNice.'<br />';

        } else {

            echo 'Your dates are available';

            $sqlinsert = "INSERT INTO bookings (name, email, tel, roomid, date) values ";
            // Loop between timestamps, 24 hours at a time
                for ( $i = $arrive; $i <= $depart; $i = $i + 86400 ) {
                    $bookedDates =date('Y-m-d', $i ); 
                    // Constructing the insert query
                 $sqlinsert .= " ('$name', '$email', '$tel', '$roomId', '$bookedDates'),";
            }

            $bulk_insert_query = rtrim($sqlinsert, ","); // to remove last comma
            $resultinsert = $conn->query($bulk_insert_query); 
            ?>


            <p>Your booking has been received for: <br />
            Please wait for a confirmation email on: <?php echo $email; ?>

            </p>



        <?php
        // header('refresh:3; url=book.php?id='.$id.'#booking-form');

        }// if  
}   // for

}

Please can someone help out by showing me an example code of how to solve this issue. I am still a newbie at PHP.

Make an SQL request, fill the response into an array (which you already do), make a function that takes an array as an argument.发出 SQL 请求,将响应填充到一个数组中(您已经这样做了),创建一个将数组作为参数的函数。

function checkDate($dates){ //dates is the array you get from your SQL
   foreach($dates as $date){
     if($_POST['date'] == $date){
     return false;
     }
   }
return true;
}

If you get true out of this function you can enter that date into your database, if it is false then you already have that date booked.如果你从这个函数中得到 true,你可以将该日期输入到你的数据库中,如果它是 false,那么你已经预订了那个日期。

I don't know how to change the insert code to a prepared statement, because I found this bulk insert code off the internet, and honestly don't know how to convert it to a prepared statement.我不知道如何将插入代码更改为准备好的语句,因为我在互联网上找到了这个批量插入代码,老实说不知道如何将其转换为准备好的语句。

I have managed to figure it out:我设法弄清楚了:

<?php
            $sql = "
            SELECT date
            FROM bookings
            WHERE roomid = $roomId;
            ;";

            $result = $conn->query($sql);
            $alreadyBooked = array();

            if ($result->num_rows > 0) {
                // output data of each row
                while($row = $result->fetch_assoc()) {
                    $alreadyBooked[] = $row['date'];
                } // while
            } //  num rows






            if(isset($_POST['submit'])){

                $name = $_POST['name'];
                $email = $_POST['email'];
                $tel = $_POST['tel'];
                $arrive = strtotime($_POST['arrive']);
                $depart = (strtotime($_POST['depart'])) - 86400;
                ?>

                <a name="booking-form"></a> 
                <h2>Viewing <?php echo $roomname; ?></h2>
                <h3>You have chosen the following dates: </h3>



                <?php
                // show which dates the user chose
                for ( $i = $arrive; $i <= $depart; $i = $i + 86400 ) {
                        echo $bookedDatesecho = date('D, j M Y', $i ).'<br />';
                 }

                // save the dates the user chose into an array
                for ( $i = $arrive; $i <= $depart; $i = $i + 86400 ) {
                    $bookedDates[] = date('Y-m-d', $i );
                }                   

                // checking dates chosen from form with dates in the database
                $compareDateResult = array_intersect($alreadyBooked,$bookedDates);

                // if statement to check whether the dates chosen are available or not and then do something
                if (empty($compareDateResult)){

                    // save booking to the database
                    $sqlinsert = "INSERT INTO bookings (name, email, tel, roomid, date) values ";
                    // Loop between timestamps, 24 hours at a time
                        for ( $i = $arrive; $i <= $depart; $i = $i + 86400 ) {
                            $bookedDates =date('Y-m-d', $i ); 
                            // Constructing the insert query
                         $sqlinsert .= " ('$name', '$email', '$tel', '$roomId', '$bookedDates'),";
                    }

                    $bulk_insert_query = rtrim($sqlinsert, ","); // to remove last comma
                    $resultinsert = $conn->query($bulk_insert_query);   
                    ?>
                    <p>Your booking has been received for: <br />
                    Please wait for a confirmation email on: <?php echo $email; ?></p>

                <?php 
                } else { ?>

                    <h3>These dates are not available:</h3>


                    <?php 
                    foreach ($compareDateResult as $value) {
                        //echo 'the date: '.$value.' <br />';
                        $value2 = strtotime($value);
                        echo date('D, j M Y',$value2).'<br />'; 
                    } // foreach
                    ?>
                    <p><a href="book.php?id=<?php echo $id; ?>">Please try again</a></p>

                <?php   
                } // if                 




             } else {  ?>



                <h2>Booking Form</h2>       
                <form id="booking-form" method="post" action="#booking-form" />

                    <input type="hidden" name="<?php echo $roomId; ?>" />

                    <label>Name</label><br />
                    <input type="text" name="name" required />
                    <div class="clear20"></div>

                    <label>Email</label><br />
                    <input type="email" name="email" required/>
                    <div class="clear20"></div>

                    <label>Telephone</label><br />
                    <input type="text" name="tel" required />
                    <div class="clear20"></div>

                    <label>Arrive on: </label>
                    <input type="date" name="arrive" required/> at 2pm
                    <div class="clear20"></div>

                    <label>Depart on: </label>
                    <input type="date" name="depart" required/> at noon
                    <div class="clear20"></div>

                    <input type="submit" name="submit" value="Book &raquo;"/>

                </form>

            <?php }     ?>      

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM