How to show date and time in php

Asked

Viewed 1,540 times

2

How do I show the date and time after the user sends a message?

I created in the database a column called 'date' of type 'DATETIME'.

In php I used the following code to insert the data:

Inserir.php

$sql = "INSERT INTO autoriza (ID, data) VALUES( '$id', 'NOW()')";
$acao_sql = $mysqli->query($sql);

Lista.php

$sql = "SELECT * FROM autoriza ORDER BY ID DESC";
$acao_sql = $mysqli->query($sql);
while ($lista = $acao_sql->fetch_array(MYSQLI_ASSOC)){
       echo "Recado enviado em: ".$lista['data']; 
}

The above result shows: 0000-00-00 00:00:00

  • 1

    I managed using the following code: date_default_timezone_set('America/Sao_paulo'); $mysqldata = new Datetime(); $data = $mysqldata->format(Datetime::ISO8601);$sql = "INSERT INTO authorizes (ID, date, name, Cpf) VALUES( '$id', '$data', '$name', '$Cpf')"; $acao_sql = $qli->query($sql);

2 answers

4


Use without Apas in function NOW() and put id with auto_increment on your table:

Inserir.php

$sql = "INSERT INTO autoriza (data) VALUES(NOW())";
$acao_sql = $mysqli->query($sql);

He’s not recording one datetime correctly because of the simple quotes ...


To format a datetime use the function date_format, as shown below.

Lista.php

$sql = "SELECT date_format(data, '%d/%m/%Y') as data FROM autoriza ORDER BY ID DESC";
$acao_sql = $mysqli->query($sql);
while ($lista = $acao_sql->fetch_array(MYSQLI_ASSOC)){
       echo "Recado enviado em: ".$lista['data']; 
}

References

  • Thanks! It worked! Now I need to put in order the date DIA - MES - ANO. I will search here.

  • 1

    Consgeui format the date like this: <?php $data = date_create($list['data']); echo date_format($data, ’d-m-Y H:i:s'); ?>

  • @Gustavocave, I changed the answer adding how I could work with dates for presentation of results ...

0

Has the function date() php native.

More information:
http://www.php.net/manual/en/book.datetime.php

To register id you can use the PRIMARY KEY AUTO INCREMENT

More information:
http://www.w3schools.com/sql/sql_autoincrement.asp
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
http://www.w3schools.com/sql/sql_primarykey.asp

<?php
$data = date("Y-m-d H:i:s"); //formato 2014-05-04 18:00:00
$sql = "INSERT INTO autoriza (data) VALUES('".data."')"; 
$acao_sql = $mysqli->query($sql);

//mostra
$sql = "SELECT * FROM autoriza ORDER BY ID DESC"; 
$acao_sql = $mysqli->query($sql);
while ($lista = $acao_sql->fetch_array(MYSQLI_ASSOC)) { 
 echo $lista['data'];
}
?>

Browser other questions tagged

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