Use DateTime Stamp Appropriately in PHP/MySQLi
Submitted by Yorkiebar on Monday, July 14, 2014 - 03:38.
Introduction:
This tutorial is on how to use timestamps properly in PHP and MySQLi to sort information from databases in to the correct order.
What's a Timestamp?
A timestamp is a data type in PHP and MySQL(i) which is used to hold the correct format of a specified date, time, or date and time together.
Database:
To enable a database table to hold a timestamp we can first create a database, named 'fln', then create a table named 'test', and give it the following column structure...
id, int, 5 length, primary key, auto increment
date, datetime, 255 length
Now we are ready to code some PHP for our table.
PHP Date:
We can get the current date through PHP's 'date' function (handy!)...
This will put the standard datetime stamp format in to our new 'date' variable. The order of information will be;
Year:Month:Day Hour:Minutes:Seconds
There are a load of other combinations, all of which can be found at the PHP official manual, date (http://php.net/manual/en/function.date.php).
Modifications:
We can also modify our date by adding an additional parameter to our 'date' function using another 'strtotime', StringToTime, function of PHP...
The above code would add two hours to the current date and time. While the below code would subtract four minutes from the current date and time.
Table Injection:
Now we are ready to inject our new date in to our table. We first create the connection to our MySQL(i) service...
Next we run the query to inject the data in to a new row on our 'test' table...
We could also use an if statement to output an error/success message, like so;
Finished!
- $con = mysqli_connect("localhost", "root", "", "fln"); //Service server, Username, Password, Database
- echo 'Success';
- }else
- echo 'Failed';
Add new comment
- 540 views