0

I'm going crazy to figure out how to do to make a php script that allows me to know the date of the entered data in the database (text). The query that adds the data is structured in this way:

$query = "INSERT INTO column (Data) VALUES ( NOW() )";

In the database I created a date field of type timestamp. Instead the script that retrieves the data from the database is structured so

$query = mysql_query("SELECT Data FROM table WHERE id = ".$_REQUEST['id'].";");
while ($Row = mysql_fetch_array($query)) {
    echo "Created:".$Row[0];
}

The output is always 01/01/1970 that is the Unix Date. How to solve? please I'm going crazy!!! could you post the correct code? Many Thanks!

vascowhite
  • 18,120
  • 9
  • 61
  • 77
Simone Cognom
  • 39
  • 1
  • 5

2 Answers2

0

A better solution would be to create the table with a timestamp default. That way you would not have to insert anything into the table as far as the timestamp column is concerned.

To do this you can either do the following on table creation,

 `created` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

The above will auto set the created column to the time that the row data was inserted into the column.

If you would like to have the column row auto update itself whenever the row is updated you can also do the following; this would be useful for a column which say for a forum displays the last updated or edited time of that post.

`updated` TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,

You can read more about this here, http://dev.mysql.com/doc/refman/5.0/en/date-and-time-types.html.

Upon retrieving the value, to get a date like output from php use the date function.

More information on the date function can be found here http://php.net/manual/en/function.date.php.

It is also worth noting that your current code is not very well written and is open to SQL injection (http://en.wikipedia.org/wiki/SQL_injection), I would advise you to learn php's PDO (http://php.net/manual/en/book.pdo.php).

PDO also has the advantage that if in the future you change databases it is not a very hard to do task while using PDO.

GriffLab
  • 2,076
  • 3
  • 20
  • 21
  • Hi, i had already set the current_timestamp default. http://i41.tinypic.com/eumpf5.png . I do not care modification date. could you tell me the complete instruction to convert the date in readable format. The date is stored into database in this format 2013-06-06 16:30:41 P.S. How to understand if the code is open to SQL Injection? Sorry for my english – Simone Cognom Jun 06 '13 at 14:29
0

could try this

$query = "INSERT INTO table_name (Data) VALUES (CURRENT_TIMESTAMP())";

The problem seems to be that you're not inserting data properly which is why you're getting back that 0 Day time stamp.

TheSnooker
  • 935
  • 2
  • 11
  • 24