Insert Form DATE value into MySQL in PHP

How to Insert Form DATE value into MySQL in PHP

 


 

 

This tutorial shows how to insert HTML date widget value into MySQL database in PHP, 

when the user selects the date from the HTML form date widget/date picker, it will display the date in a dd-mm-yyyy format, whereas MySQL date format is yyyy-mm-dd. For this, PHP converts the date into MySQL supportable format and inserts into the database. 

This is explained step by step in this tutorial.
Where we will take the input type as date and insert date value in MySQL database using PHP when the form submitted by using method POST.

For this, I have used a simple HTML Form for user interface.
 

Step 1:
Create a table:
tbl_users in your Database (MySQL) as follows:
 

--
-- Table structure for table `tbl_users`
--

 CREATE TABLE `tbl_users` (

  `id` int(11) NOT NULL,
  `username` varchar(30) NOT NULL,
  `dob` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

 

Step 2:
 

Create an index.php and copy the below code, change database details according to yours and run in browser.

index.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CODING-ZON Tutorial</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container">

<h1>How to Insert Form DATE Value into MySQL in PHP</h1>
<div class="row justify-content-center">
<div class="col-6">

<?php
session_start();
$conn = mysqli_connect("localhost","root","","usersdb");

if(isset($_POST['submit']))
{
$username = $_POST['name'];
 $dob = date('Y-m-d', strtotime($_POST['dob']));

$query = "INSERT INTO tbl_users (username,dob) VALUES ('$username','$dob')";
$result = mysqli_query($conn, $query);
if($result)
echo "Record Added";
}
else
{

echo "<font color='green'>Data added Successfully.";
}

?>


<form action="" method="POST">
<div class="form-group mb-3">
<label for="">Username</label>
<input type="text" name="name" class="form-control" />
</div>
<div class="form-group mb-3">
<label for="">Date of Birth</label>
<input type="date" name="dob" class="form-control" />
</div>
<div class="form-group mb-3">
<button type="submit" name="submit" class="btn btn-primary">Add Record</button>
</div>
</form>
</div>

</div>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

 


 Checkout the demo here:

 


 



 

Comments

Popular posts from this blog

Using javascript pass form variables to iframe src

Creating a new PDF by Merging PDF documents using TCPDF

Import excel file into mysql in PHP