Save and display date in PHP and MySQL

by Anwarul Haque December 24, 2020

php mysql

In this post i will show you easiet way to store date in mysql anddisplay it in different formats using PHP. MySQL default date format is Y-m-d H:i:s (e.g 2018-03-16 14:20:01). If you want to store only date, use DATE data type. If both date and time, then use DATETIME datatype. 

create table post (         id int unsigned primary key auto_increment,       title varchar(255),    created date ); 
To add record using PHP, first convert the php current date to MySQL date format;
// Current date only   $created = date('Y-m-d');   // Current date and time   $created = date('Y-m-d H:i:s');   insert into post(title,created) values ('Web design','$created'); 
Fetch the record and display in page: Below code will display the date in default MySQL date and datetime format, means as stored th the table column. e.g: 
foreach ($post as $p) {   echo $p['title'];   echo $p['created']; }  
But if you want to display date in different format, first convert it into unix timestamp and use PHP date function. For example, if display format is 16-03-2018,   So, using PHP date() and strtotime() function, you can convert show the date in any date  formats.    
foreach ( $post as $p)  {       echo $p['title'];   echo date('d-m-Y',strtotime($p['created')); } 

Javascript reference and undefined error