Entering HTML Date for SQL using php

I am trying to use a form written in HTML to enter "Name" and "Date" into an SQL database.

As for connecting to SQL, everything is fine. Simply, using the HTML5 date input type (which includes a drop-down calendar), data and PHP do not seem to be displayed. When I enter the data in the SQL table, a "Name" appears, but the "Date" remains empty. I have placed part of my code below. The form is input.html, and the data processing code is table.php. The database name is the users, and the table name is the staff.

input.html

<html> <form action='table.php' method='POST'> Name <input type="text" name="name"> <br /> Date of Expiry <input type="date" name="date1"> <br /> <input type="submit" name="submit" value="Submit"> <br /> </form> </html> 

Table.php

 <?php $name = $_POST["name"]; $date1 = $_POST["date1"]; $servername = "exampleserver.net"; $uname = "exampleusername"; $pass = "password"; $dbname = "users"; $errors = array(); $conn = new mysqli($servername, $uname, $pass, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if(mysqli_query($conn,"INSERT INTO staff (`name`, `date1`) VALUES('$name','$date1')")) { header("Location: http://newpageafterdataentry.com"); die(); } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?> 
+5
source share
1 answer

You can use strtotime () to convert to a timestamp and date () to format before saving to mysql DB. Try the following:

 $day1 = strtotime($_POST["date1"]); $day1 = date('Ymd H:i:s', $day1); //now you can save in DB 

Full code should be:

 <?php $name = $_POST["name"]; $day1 = strtotime($_POST["date1"]); $day1 = date('Ymd H:i:s', $day1); //now you can save in DB $servername = "exampleserver.net"; $uname = "exampleusername"; $pass = "password"; $dbname = "users"; $errors = array(); $conn = new mysqli($servername, $uname, $pass, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } if(mysqli_query($conn,"INSERT INTO staff (`name`, `date1`) VALUES('$name','$date1')")) { header("Location: http://newpageafterdataentry.com"); die(); } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?> 
+3
source

All Articles