Storing dates in mysql

Discussion in 'PHP' started by okgaz, Sep 18, 2007.

  1. #1
    Hi.

    Ok I want to store the date that entries are added to my database in such a way that I can easily return all of the entries added within the last week, month or year.

    Does anybody know the best way to do this with PHP & MySql?

    Thanks!
     
    okgaz, Sep 18, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    I always work with INT fields, and just store the UNIX timestamp. There are MySQL functions for this, but I always felt more comfortable using timestamps.

    
    INSERT INTO table_name (dateline) VALUES (" . time() . ")
    
    Code (sql):

    Get entries added within one week
    
    SELECT * FROM table_name WHERE dateline >= " . strtotime('-1 Week')
    
    Code (sql):
     
    nico_swd, Sep 18, 2007 IP
  3. PHPGator

    PHPGator Banned

    Messages:
    4,437
    Likes Received:
    133
    Best Answers:
    0
    Trophy Points:
    260
    #3
    Make sure you are submitting dates into a field that is set as "DATE". This way you can retrieve the table with PHP and "order by date". This is really a MySQL query issue and not a PHP issue if you do it properly. PM me if you need further help. :)
     
    PHPGator, Sep 18, 2007 IP
  4. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #4
    I would use a timestamp. In my experience it is a much easier method of sorting and arranging date related queries, because the date is stored in a single incrementing number.
     
    jestep, Sep 18, 2007 IP
  5. okgaz

    okgaz Well-Known Member

    Messages:
    450
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    128
    #5
    Thanks for your advice everyone. I decided to sort it by timestamp in the end :)
     
    okgaz, Sep 20, 2007 IP
  6. benajnim

    benajnim Peon

    Messages:
    20
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    I use the Now() sql keyword for updating a timestamp:

    update table set created_date = Now() where table_id = 1;

    FWIW, MySQL date handling is inferior to Postgres. I'm not trying to start a flamewar, but the date manipulation functions in MySQL are clumsy compared to other database engines.
     
    benajnim, Oct 17, 2007 IP