PHP Timestamps time()

One of the most common ways to capture the current time in PHP scripting is by using the time() function. This returns the current timestamp which is the number of seconds after a certain date and time in the past. You can use this when entering a mysql query to note the current time of whatever action you are capturing.

We must be connected to a Mysql database in order to submit the value(s) to the database. You can see how to connect to a mysql database here.

For example, lets say we want to capture the current time of when a form is submitted:

<?php

if($_POST["submit"]){
// form is submitted
$username = trim($_POST["username"];
$password = md5(trim($_POST["password"]));
// trim the values
$time = time(); // capture the current timestamp to record the time.

// connect to mysql database here!
// granted we are already connected to a mysql database, submit the query
$sql = mysql_query("INSERT INTO users (username,password,timestamp) VALUES ('$username','$password','$time')") or die(mysql_error());
}

// username,password, and time submitted to the database

If we wanted to grab the time that a user is submittted to the database (their registration date/time) we would just use a Mysql query to select the timestamp where the Username field matches a specified value. We will use the date() function to echo the timestamp into a date format. We will use the m/d/Y format:

  • d – Represents the day of the month (01 to 31)
  • m – Represents a month (01 to 12)
  • Y – Represents a year (in four digits)

View a complete list of the PHP date() format list here!

Like so:

<?php
$sql = mysql_query("SELECT timestamp AS time FROM users WHERE username = '$username'") or die(mysql_error());
if(mysql_num_rows($sql) > 0){
$row = mysql_fetch_assoc($sql);
echo "You joined on: ".date("m/d/Y",$row['time']).".";
} else {
echo "User has not joined!";
}
?>

This will output the code as such:

You joined on: 05/31/2010.

1

Popularity: 2% [?]

0saves
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Filed Under: PHPTutorialsWeb Programming

Tags:

RSSComments (1)

Leave a Reply | Trackback URL

Leave a Reply




If you want a picture to show with your comment, go get a Gravatar.

The tutorials and scripts found on bgallz.org are for training purposes only, use to your discretion.