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.

SQL: Insert current time or timestamp

This entry is part 11 of 20 in the series SQL Tutorial

It is common for developer to insert a timestamp into each record marking the time a record is created.

With timestamp, we could for example, know when a purchase of an item is made.

In the example below, we make a slight modification to the example sql fiddle and add a time that a record is created.

CREATE TABLE supportContacts 
 id int auto_increment primary key, 
 type varchar(20), 
 details varchar(30), 
 current datetime

INSERT INTO supportContacts
(type, details, current)
('Email', '', now()),
('Twitter', '@sqlfiddle',now());

Notice that we use a variable current with a datetime datatype.  The timestamp is inserted by now().

Sometimes, we use select now() to check the current time of the server system.