Christian Tucker
Christian Tucker

Reputation: 627

How can I get the current date?

I've done some researching, but I can't really find anything for the format that I'm wanting. Please go easy on me as this is my second day learning PHP and I'm working on a fairly large project to learn.

I have a SQL Database using the 'Date' type, which follows the yyyy-mm-dd format.

My current SQL statement does this,

$query = "INSERT INTO $tbl_name (Date, Amount) VALUES ('now()', '$Amount')";

However, this doesn't update the date, and all of my entries are showing 0000-00-00

I'm not sure what I'm doing wrong.

Upvotes: 0

Views: 142

Answers (4)

Gergo Erdosi
Gergo Erdosi

Reputation: 42028

You can also define your table to use CURRENT_TIMESTAMP as default value:

CREATE TABLE `example` (
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
  `modified_at` DATETIME ON UPDATE CURRENT_TIMESTAMP
)

DATETIME can be used only from MySQL 5.6.5. In previous versions you need to use the TIMESTAMP type:

CREATE TABLE `example` (
  `created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  `modified_at` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

Upvotes: 0

Knoweldges
Knoweldges

Reputation: 72

There is many ways to do that.

1. Using the MySQL function "NOW()".

You can simply put NOW() on the place where date should be. NOW() is a MySQL function who return the date formated such as you request.

2. Using the PHP function "date()".

You can also use the date() function which comes with PHP, to perform what you want, juste wrote something like that :

$date = date('Y-m-d');
$query = "INSERT INTO $tbl_name (Date, Amount) VALUES ('$date', '$Amount')";

Upvotes: 1

Julian F. Weinert
Julian F. Weinert

Reputation: 7560

You have to remove the single quotes! Additionally you could use the CURRENT_DATE constant or create your table with ON UPDATE CURRENT_TIMESTAMP

Upvotes: 1

max
max

Reputation: 10444

try this:

$query = "INSERT INTO $tbl_name (Date, Amount) VALUES (now(), 123)";

Upvotes: 1

Related Questions