How to post date and time using type '' datatime '' in sql

1

PHP:

$date = new DateTime();
print_r ($date);

result:

DateTime Object ( [date] => 2017-11-07 15:51:26.000000 [timezone_type] => 3
[timezone] => America/Sao_Paulo )

Okay, see you later.

Database (sql). Extras table:

Table"extras"

I need to know what standard the datetime type uses to know how to post the date and time information in the database.

Below the tests performed, and the answers obtained:

TEST 1:

 $postdate = $conect -> query("INSERT INTO extras (data) values ('{$date['date']}')");

TEST2:

$postdate=$conect->query("INSERT INTO extras (data) values ('{$date}')");  

Thank you in advance

    
asked by anonymous 07.11.2017 / 19:12

2 answers

1

There are several functions to write the date in SQL, one I would use would be the CURDATE (); it picks up the current date. It would look something like this:

  $postdate = $conect -> query("INSERT INTO extras (data) values (CURDATE()); 

Note: Curdate () by default will return Year / Day / Month. If you want to format, use:

  date_format(curdate(), '%d/%m/%Y')
    
07.11.2017 / 19:23
0

The object DateTime has no cast string . It is therefore necessary to use the format method to display the date on the desired output.

The format used in MYSQL to insert dates is Y-m-d H:i:s .

$sql = sprintf('INSERT INTO tabela (data) VALUES ("%s")', $data->format('Y-m-d H:i:s'));

$query->execute($sql)

On the other hand, if you enter the current date, it might be cool for you to use NOW() instead of PHP conversion.

$sql = 'INSERT INTO tabela (data) VALUES(NOW())';
    
07.11.2017 / 19:22