PHP Form & MySQL: Enter data through form

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

1Independence DayWill Smith1996

We will build a form and enter the above record to the table.

We will need to go through the usual steps before executing the insert query string.

The steps are:

  • Set up the db connection
  • Create the database
  • Use the database
  • Create the table

And finally, we execute the query string in line 46.


<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);




Using what we have learnt about php form and db insert, the above script could be developed quite easily.

The form generated by the above script is as shown below:


After running the above script, and typing in the necessary inputs we can check the database using Toad.


Series Navigation<< PHP Form & MySQL: Insert a record through variable
PHP Form & MySQL: Getting the date from a form >>