How to post date and time using datatime type in sql

Asked

Viewed 291 times

1

PHP:

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

outworking:

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

OK so far.

Database (sql). Table "extras":

Tabela "extras"

I need to know which pattern the datetime type uses, to know how to post the date and time information in the bank.

Below the tests performed, and the responses obtained:

TEST 1:

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

TEST 2:

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

inserir a descrição da imagem aqui

Ever since I thank

  • have to modify to USA date mode to enter into Y-m-d database, correct @rray ?

  • Yes, you can just use $data = date('Y-m-d H:i:s');

  • I think there’s something not getting into my head. If I use "$data = date('Y-m-d H:i:s');", when I retrieve the information it will be just any string. To use it like this wouldn’t make a difference using datetime, or a varchar.

  • 1

    vc do not need to write a php Datetime object to the database, if it is recorded as varchar it will not sort or search the results correctly. Relacioanda: Varchar or Datetime?

2 answers

1

There are several functions to save the date in SQL, one that I use would be CURDATE(); it takes the current date. It would look like this:

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

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

  date_format(curdate(), '%d/%m/%Y')

0

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

The format used in MYSQL to enter 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 are going to enter the current date, it might be nice for you to use NOW() instead of converting from PHP.

$sql = 'INSERT INTO tabela (data) VALUES(NOW())';

Browser other questions tagged

You are not signed in. Login or sign up in order to post.