How to put the current date and time in a datetime field? [closed]

2

I have a date field in a table that is of type datetime and I want to put the current date of my server.

Ihavetriedeverything,withNOW()intheinsertionSQL,butthenIsawthatitdoesnotwork.IalreadytriedtochangetheDEFAULToffielddatetoCURRENT_TIMESTAMPandnothing.

InPHPIhavealreadytriedwiththefunctiondate,andgmdate,

date("Y-m-d H:i:s");
gmdate("Y-m-d H:i:s");

I still have 0000-00-00 00:00:00 in the database, this is when I try to insert a record in the table.

    
asked by anonymous 19.01.2016 / 11:01

1 answer

2

Well, I do not know if that's exactly what I understood. Suppose you have the following table:

CREATE TABLE 'test'.'tasks' (
    'id' INT NOT NULL AUTO_INCREMENT,
    'created_at' DATETIME NULL,
    PRIMARY KEY ('id')
);

To insert a record with the current date of the server, just the following command:

INSERT INTO tasks (created_at) VALUES (now()); 
  

mysql > select * from tasks;
  + ---- + --------------------- +
  | id | created_at

  + ---- + --------------------- +
  | 1 | 2016-01-19 11:49:58

  + ---- + --------------------- +
  1 row in set (0.00 sec)

Using PHP (with PDO), just do the following:

<?php

// algo mais ou menos como: 2016-01-19 11:56:30
$data_actual = date('Y-m-d H:i:s');


$sql = "INSET INTO tasks(created_at) VALUES (:created_at)";
$stmt = $pdo->prepare($sql);

$stmt->bindParam(':created_at', $data_actual);
$stmt->execute();

UPDATE:

Note: By error, you are trying to add a value of type datetime into a field of type date

UPDATE 2:

By the table structure, the field in name date is or may cause problems. Rename this field. Because date is used as a MySQL data type ( link ).

After you do this update, you can insert it this way:

INSERT INTO tasks (created_at) VALUES (now()); 
    
19.01.2016 / 11:52