0

when inserting a date into a MySQL DB using PHP what is the best format so that I can sort by date later. I started using

$current_time = date("Y-m-d");

Is this the best practice?

3 Answers 3

3

If you are able to control your database fields then I would recommend using MySQL's built in Timestamp data type. You can set it to the current time by default.

CREATE TABLE IF NOT EXISTS `your_table` (
    `date` timestamp NOT NULL default CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

If not then I would reccomend just storing the default PHP Unix formatted timestamp in an integer field.

$current_time = time();
Sign up to request clarification or add additional context in comments.

Comments

1

The database handles dates internally for storing and sorting. Y-m-d format is good

Comments

0

You do not ever need to generate the current date or time in PHP to insert it into a query. Use the MySQL constants CURRENT_DATE and CURRENT_TIMESTAMP in the query instead.

INSERT INTO table (name, date) VALUES ('Bob', CURRENT_DATE)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.