Use DateTime Stamp Appropriately in PHP/MySQLi

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!)...
  1. $date = date("Y:m:d H:i:s");
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...
  1. $date = date("Y:m:d H:i:s", strtotime("+2 hour"));
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.
  1. $date = date("Y:m:d H:i:s", strtotime("-4 minute"));
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...
  1. $con = mysqli_connect("localhost", "root", "", "fln"); //Service server, Username, Password, Database
Next we run the query to inject the data in to a new row on our 'test' table...
  1. mysqli_query($con, "INSERT INTO `test` VALUES('', '$date')");
We could also use an if statement to output an error/success message, like so;
  1. if(mysqli_query($con, "INSERT INTO `test` VALUES('', '$date')")) {
  2. echo 'Success';
  3. }else
  4. echo 'Failed';
Finished!

Add new comment