2013-10-21 48 views
0

我正在使用jQuery的Datepicker。提交頁面時,如果未輸入任何值,則需要將NULL插入到SQL表中。相反,它目前插入1900-01-01 00:00:00.000。是否有可能通過NULL在我的插入使用jQuery的Datepicker?jQuery Datepicker如果留空即插入NULL

在多年前創建的SQL表中,數據類型爲datetime,且Allow Nulls設置爲Yes。默認值或綁定中沒有設置任何值。

此外,只是要注意,我正在做錯誤檢查,並考慮到SQL注入的可能性。只是爲了防止集羣在這裏,並保持代碼簡單/易於閱讀,我沒有在這裏包括它。

PHP

$sDate = $_POST['sDatepicker']; 
$eDate = (!empty($_POST['eDatepicker'])) ? $_POST['eDatepicker'] : NULL; 

$insert = "INSERT INTO table1 (sdate, edate) 
      VALUES ('$sDate', '$eDate')"; 
// Connection, error checking, execution, etc. using ODBC 

我也有嘗試:

if (empty($_POST['eDatepicker'])) { 
    $insert = "INSERT INTO table1 (sdate, edate) 
       VALUES ('$sDate', NULL)"; 
} else { 
    $eDate = $_POST['eDatepicker']; 
    $insert = "INSERT INTO table1 (sdate, edate) 
       VALUES ('$sDate', '$eDate')"; 
} 
// Connection, execution, etc. 

我也嘗試添加一個隱藏字段,並使用它,如果(empty($_POST['eDatepicker']))所以甚至不使用的日期選擇器,如果它是空的。即使我這樣做,它仍然插入相同的1900-01-01 00:00:00.000

HTML/jQuery的

<div> 
    <label>Start Date:</label> 
    <input type="text" id="sDatepicker" name="sDatepicker" class="required" /> 
</div> 
<div> 
    <label>End Date:</label> 
    <input type="text" id="eDatepicker" name="eDatepicker" /> 
    <input type="submit" value="Submit" id="btnSubmit" /> 
</div> 

$('#sDatepicker, #eDatepicker').datepicker({ 
    changeMonth: true, 
    changeYear: true, 
    dateFormat: "mm/dd/yyyy" 
}); 

我也試過在jQuery的分裂日期選擇器的和添加defaultDate: null但也不能工作。

+0

你嘗試使用'NULL'在你的數據庫的默認值? –

+0

默認值或綁定中沒有設置。對不起,如果這不是你的意思,我有最小的數據庫經驗。如果不是我會在哪裏找到? – Brian

+0

如果您使用的是phpMyadmin,請在您的表格字段中查看您希望成爲「NULL」並查找「Default」的內容 - 如果沒有內容,只需在其中輸入「NULL」一詞並保存即可。 –

回答

1

您可以簡單地檢查字段值是否爲「1900-01-01 00:00:00.000」並插入null。

if ($_POST['eDatepicker']=="1900-01-01 00:00:00.000") { 
    $insert = "INSERT INTO table1 (sdate, edate) 
       VALUES ('$sDate', NULL)"; 
} 

更新: 由於此值不是從datepicker.you未來如果默認值以dB爲單位設置應該檢查。

速戰速決是一個default date添加日期選擇器,並檢查在PHP

$('#sDatepicker, #eDatepicker').datepicker({ 
    changeMonth: true, 
    changeYear: true, 
    dateFormat: "mm/dd/yyyy" 
    defaultDate:"01/01/1900" //some date 
}); 

if ($_POST['eDatepicker']=="01/01/1900") { 
     $insert = "INSERT INTO table1 (sdate, edate) 
        VALUES ('$sDate', NULL)"; //insert null 
    } 
+0

似乎應該工作,但結果相同。它實際上發佈了我試圖在if語句中檢查的「」,但同樣的結果。 – Brian

+0

@Brian更新了答案 – Arunu