Reputation: 1184
I'm using jQuery's Datepicker. When the page is submitted, if no value is entered, I need to insert NULL
into the SQL table. Instead it is currently inserting 1900-01-01 00:00:00.000
. Is it possible to pass NULL
in my insert using jQuery's Datepicker?
In the SQL table, which was created years ago, the Data Type is datetime
and Allow Nulls is set to Yes. Nothing is set in Default Value or Binding.
Also, just to note, I am doing error checking and taking into account the possibility of SQL injection. Just to try and prevent cluster here and keep the code simple/easy to read, I'm not including it here.
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
I have also tried:
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.
I also tried adding a hidden field and using it if (empty($_POST['eDatepicker']))
so the datepicker is not even used if it is empty. Even when I do this, it still inserts the same 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"
});
I also tried splitting the datepicker's up in the jQuery and adding defaultDate: null
but that did not work either.
Upvotes: 1
Views: 3343
Reputation: 2349
you can simply check if the field value is "1900-01-01 00:00:00.000" and insert null .
if ($_POST['eDatepicker']=="1900-01-01 00:00:00.000") {
$insert = "INSERT INTO table1 (sdate, edate)
VALUES ('$sDate', NULL)";
}
Update: Since this value is not coming from datepicker.you should check if default value is set in db.
A quick fix is to add a default date to datepicker and check that in php
$('#sDatepicker, #eDatepicker').datepicker({
changeMonth: true,
changeYear: true,
dateFormat: "mm/dd/yyyy"
defaultDate:"01/01/1900" //some date
});
and
if ($_POST['eDatepicker']=="01/01/1900") {
$insert = "INSERT INTO table1 (sdate, edate)
VALUES ('$sDate', NULL)"; //insert null
}
Upvotes: 1