I have a file that saves a date input into my database.
Here is my HTML and JS codes:
<form id="myForm">
Date:<input type='date' name ='date' required id="date">
<input type="button" name="submits" value="submit" id="btn_submit">
</form>
<script>
$(document).ready(function() {
$("#btn_submit").click(function() {
var dates = $("#date").val();
if (dates == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
$.post("datedatabase.php", {
date1: dates
}, function(data) {
alert(data);
$('#myForm')[0].reset(); // To reset form fields
});
}
});
});
</script>
PHP code:
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("date", $connection);
$date2=$_POST['date1'];
$query = mysql_query("INSERT INTO date_use (id,dateUSE,stock) VALUES('',$date2,'')");
if($query){
echo "Data Submitted succesfully";
}
mysql_close($connection); // Connection Closed.
?>
And when I test it, I saved it to my database and it is successful BUT the data inputted in my database is an empty date like this --> 0000-00-00
. Whats wrong in my code?
Try outputting the string you receive as date2 just before the query and check, the string has the correct format.
Regards
Try this change:
$date = $_POST['date1'];
$date2 = strtotime($date);
$date2 = date('Y-m-d', $date2);
To convert the date string from mm/dd/yyyy to yyyy-mm-dd you can quickly go this way:
list($month, $day,$year)=explode("/", $date2);
$date2 = $year."/".$month."/".$day;
This will get your result with just a bit of string manipulation
Or you can go through date conversion to a timestamp as another answer is suggesting.