PHP Form & MySQL: Getting the date from a form

This entry is part 3 of 3 in the series PHP Form & MySQL

Datetime is a very common data type in database.  There are various functions available in php and mysql for manipulating the datetime variables.

Here, we have a form for us to input the release date of a movie.


<form action='' method='post'>
    Movie: <input type='text' name='title'><br>
    Actor: <input type='text' name='actor'><br>
    Release Date yyyy-mm-dd: <input type='text' name='release_date'><br>
    <input type='submit'>


$title = @$_POST['title'];
$actor = @$_POST['actor'];
$release_date = @$_POST['release_date'];

echo "Title: " . $title . "<br>";
echo "Actor: " . $actor . "<br>";
echo "Release Date: " . $release_date . "<br>";

$mysqli = new mysqli("localhost", "root", "");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL";

$sql_db = "create database if not exists allmovie";
mysqli_query($mysqli, $sql_db);

$sql_use_db = "use allmovie";
mysqli_query($mysqli, $sql_use_db);

$sql_tb = "create table if not exists movie (id int auto_increment primary key, title varchar(30), actor varchar(50), rel_date datetime)";
mysqli_query($mysqli, $sql_tb);

$release_date = DateTime::createFromFormat('Y-m-d', $release_date);

if ($release_date) {
    $release_date = $release_date->format('Y-m-d');
    $sql_in = "insert into movie (title, actor, rel_date) values ('$title', '$actor', '$release_date')";
    mysqli_query($mysqli, $sql_in);





In this example, we have used the Y-m-d format, which is a frequently used format.  After getting the date from the form, we need to convert it to a format that we could insert into mysql.

We have used OOP style as below.  Note that even though we have asked the user to input the date in Y-m-d format, we still need the 2 statements below.

$release_date = DateTime::createFromFormat('Y-m-d', $release_date);
$release_date = $release_date->format('Y-m-d');


There is this line:

$sql_use_db = "use allmovie";

Currently we only have one database.  We could have a few datasases and this line is to let us create the table movie under the database allmovie.

Series Navigation<< PHP Form & MySQL: Enter data through form

Leave a comment

Leave a Reply