0

检查 SQL 表

这是名为“calende_bookings”的 SQL 表的结构。

  TABLE `calende_bookings`
     - `id`,
     - `id_item`,
     - `the_date`,
     - `id_state`,
     - `id_booking`,
     - PRIMARY KEY  (`id`)

目标是获取数据库中已经存在的预订日期并更新 Datepicker ui,这将禁用 Datapicker 中的这些日期范围,因此用户在预订时将无法选择它们。开始日期总是下午,所以 id_state=3 总是开始日期(从:在结果情况下),最后 id_state=1 的日期在 id_state=2 之前的日期总是最后日期(到:在结果情况下)。两个项目将单独显示,所以我需要其中一个的东西。这需要是结果(动态日期)。

var disabledArrFromTo = [ 
  { "from": "21-06-2021", "to": "26-06-2021" },
  { "from": "12-08-2021", "to": "14-08-2021" },
  { "from": .....} 
]

这是我的 Datepicker 代码,实际上可以正常工作,但是当我手动编写禁用的日期范围时。我使用了许多简单日期的示例,因此没有日期范围,它在 Datapicker 中禁用了日期,但整个脚本停止了价格计算。


$(window).load(function () {
$(document).ready(function() {

// An array of objects containing disabled date ranges
var disabledArrFromTo = [ { "from": "1-08-2021", "to": "19-08-2021" }, { "from": "23-08-2021", "to": "9-09-2021" } ];

$("#fromto").datepicker({
 beforeShowDay: function(date){
        //console.log(date);

        // For each calendar date, check if it is within a disabled range.
        for(i=0;i<disabledArrFromTo.length;i++){
            // Get each from/to ranges
            var From = disabledArrFromTo[i].from.split("-");
            var To = disabledArrFromTo[i].to.split("-");
            // Format them as dates : Year, Month (zero-based), Date
            var FromDate = new Date(From[2],From[1]-1,From[0]);
            var ToDate = new Date(To[2],To[1]-1,To[0]);

            // Set a flag to be used when found
            var found=false;
            // Compare date
            if(date>=FromDate && date<=ToDate){
                found=true;
                return [false, "red"]; // Return false (disabled) and the "red" class.
            }
        }
        
        //At the end of the for loop, if the date wasn't found, return true.
        if(!found){
            return [true, "blue"]; // Return true (Not disabled) and no class.
        }
    },
    buttonImage: "images/calendar_h.png",
    buttonText: "Arrival",
    buttonImageOnly: true,
    changeMonth: true,
    changeYear: true,
    dateFormat: "dd-mm-yy",
    altField: "#fromto",
    altFormat: "dd-mm-yy",
    gotoCurrent:  true,
    maxDate: "+2Y",
    showOn: 'both',
    yearRange: "-0:+2",
    minDate: "+1D",
    setDate: "+1",
    numberOfMonths: 1,
    onSelect: function (startDate, inst) {
            var date = startDate.split("-");
            $('#dd').val(date[0]);
            $('#md').val(date[1]);
            $('#yd').val(date[2]);
            var date = $(this).datepicker('getDate');
            if (date) {
            date.setDate(date.getDate() + 3);
            }
            $("#tofrom").datepicker("option","minDate", date)
             var startDate = new Date(parseInt($('#yd').val(),10),parseInt($('#md').val(),10)-1,parseInt($('#dd').val(),10));
            $('.dirko').text($.datepicker.formatDate('dd. mm. yy', new Date(startDate)));
            $('.ddirko').text($.datepicker.formatDate('D dd MM yy', new Date(startDate)));
        }

 });


  $("#tofrom").datepicker({
 beforeShowDay: function(date){
        //console.log(date);

        // For each calendar date, check if it is within a disabled range.
        for(i=0;i<disabledArrFromTo.length;i++){
            // Get each from/to ranges
            var From = disabledArrFromTo[i].from.split("-");
            var To = disabledArrFromTo[i].to.split("-");
            // Format them as dates : Year, Month (zero-based), Date
            var FromDate = new Date(From[2],From[1]-1,From[0]);
            var ToDate = new Date(To[2],To[1]-1,To[0]);

            // Set a flag to be used when found
            var found=false;
            // Compare date
            if(date>=FromDate && date<=ToDate){
                found=true;
                return [false, "red"]; // Return false (disabled) and the "red" class.
            }
        }
        
        //At the end of the for loop, if the date wasn't found, return true.
        if(!found){
            return [true, ""]; // Return true (Not disabled) and no class.
        }
    },


    buttonImage: "images/calendar_h.png",
    buttonText: "Departure",
    buttonImageOnly: true,
    changeMonth: true,
    changeYear: true,
    dateFormat: "dd-mm-yy",
    altField: "#tofrom",
    altFormat: "dd-mm-yy",
    gotoCurrent:  true,
    maxDate: "+2Y",
    showOn: 'both',
    yearRange: "-0:+2",
    minDate: "+1D",
    numberOfMonths: 1,
    onSelect: function (endDate, inst) {
            var eDates = endDate.split("-");
            $('#dr').val(eDates[0]);
            $('#mr').val(eDates[1]);
            $('#yr').val(eDates[2]);
            var endDate = new Date(parseInt($('#yr').val(),10),parseInt($('#mr').val(),10)-1,parseInt($('#dr').val(),10));          
            $('.cirko').text($.datepicker.formatDate('dd. mm. yy', new Date(endDate)));
            $('.ccirko').text($.datepicker.formatDate('D dd MM yy', new Date(endDate)));
    }
    
 });


 });

我从 PHP 中的数据库表中提取了日期以用于未来的日期...

/*ITEM 1*/
SELECT 
  id_item,
  id_state,
  id_date,
DATE_FORMAT (the_date, "%e-%m-%Y") AS from_the_date 
FROM calende_bookings
WHERE the_date > now()
  AND id_item = 1
  AND (id_state = 3 || id_state = 1)
ORDER by the_date ASC

我的测试 PHP 文件与数据库的连接。

<?php
$servername = "********";
$username = "***********";
$password = "***********";
$dbname = "***********";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

echo 'var disabledArrFromTo = [';


$sql = 'SELECT 
id_item, 
id_state, 
the_date, 
DATE_FORMAT (the_date, "%e-%m-%Y") AS from_the_date 
FROM calende_bookings 
WHERE the_date > now() 
AND id_item = 1 
AND (id_state = 3 
|| id_state = 1) 
ORDER by the_date ASC';

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

if ($result->num_rows > 0) {


    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo '"'. $row['from_the_date'] . '",';
    }
} else {
    echo "0 results";
}

        echo '"31-12-2076"];';

$conn->close();
?>

结果如下所示:

var disabledArrFromTo = ["25-06-2021","26-06-2021","31-12-2076"];

我需要这样的东西(startdate = item_state = 3 的日期,enddate 是 item_state = 2 之前的最后一个 item_state = 1,请查看帖子顶部的图片):

var disabledArrFromTo = [ 
  { "from": "21-06-2021", "to": "26-06-2021" },
  { "from": "12-08-2021", "to": "14-08-2021" },
  { "from": .....} 
]
4

1 回答 1

0

试试这个:准备一个包含所有禁用日期的数组

var disabledDates =['01/01/2020', '02/02/2020'];

函数 checkDayAvailable(day) { var fDay=day.getDate() + '/'+ (day.getMonth()+1) + "/" + day.getFullYear(); 返回 inArray(fDay, 禁用日期) }

$('#iDate').datepicker({ beforeShowDay: checkDayAvailable });

抱歉,我在用手机,也许我犯了一些语法错误

因此,为了从 db 中获取数据并更新 JS 数组,您可以通过两种方式进行:

在您的页面中插入 php 代码。该代码将从db中获取数据,然后将其回显到JS代码中;这可能看起来像:

<?php
//.....
//.....
$serverName = "your_server_name";
$connectionString = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionString );
if( $conn === false ) {
    die( print_r( sqlsrv_errors(), true));
}

$sql = "SELECT * FROM calendar_bookings";
$res = sqlsrv_query( $conn, $sql );
if( $res === false) {
    die( print_r( sqlsrv_errors(), true) );
}
$r="'";
while( $row = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC) ) {
      $r.=$row['the_date']."',";
}

sqlsrv_free_stmt( $res);
$r=substr($r, 0, -1);

?>

<script language="javascript">
var var disabledDates =[<?php=$r ?>];

通过使用由 ajax 调用调用的外部服务。在这种情况下,您将需要一个包含所有 php 代码的外部文件。例如(假设您在页面中使用 jquery): php 文件(我们称之为 server.php)将如下所示:

<?php 
    $serverName = "your_server_name";
    $connectionString = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
    $conn = sqlsrv_connect( $serverName, $connectionString );
    if( $conn === false ) {
        die( print_r( sqlsrv_errors(), true));
    }
    
    $sql = "SELECT * FROM calendar_bookings";
    $res = sqlsrv_query( $conn, $sql );
    if( $res === false) {
        die( print_r( sqlsrv_errors(), true) );
    }
    $r=[];
    while( $row = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC) ) {
          $r[]=$row['the_date'];
    }
    sqlsrv_free_stmt( $res);
    exit json_encode($r);
    ?>

你的js代码(假设你使用jquery,只是为了简单):

....
<script>
  $.post(
   '/server.php',
   {},
   function(data){
     try {
       var disabledDates = JSON.parse(data);
       //now do whatever you need with
    } catch(e){
       console.warn(e); 
   }
  }
);
</script>
于 2020-12-13T10:43:27.927 回答