Insert current date in Database

Asked

Viewed 271 times

1

I have a database with a table Noticias with:

  • Id (Primary key and auto_increment)

  • News (varchar, where I write the news)

  • Date(where the current date has to be, only dd/mm/yyyy)

but I never messed with dates and I don’t know how to insert in the comic with PHP.

Does anyone know anything about this that could help me?

1 answer

2


In the database, I assume MYSQL, you can use the data type DATE to store this information. I would define the table like this:

CREATE TABLE Noticias (
    id      INT,
    Noticia NVARCHAR(25000),
    Data    DATE
)

To save the current date you have two alternatives, you can do this directly in the database, at the time of INSERT using the KURDATE function();

mysql_query("INSERT INTO `Noticias` ('Id', 'Noticia', 'Data') VALUES ('1', 'Noticia de ultima hora', CURDATE())");

If you prefer you can do it in PHP as follows:

$date = date('Y-m-d');
mysql_query("INSERT INTO `Noticias` (`Id`, `Noticia`, `data`) VALUES ('$id', '$noticia' '$date')");

Regarding the date format. I would suggest saving in YYYY-MM-DD format and then, in select to get the data, you can format the date according to your preference as follows:

SELECT DATE_FORMAT(Data, '%d/%m/%Y') FROM Noticias

If you still want to store in the given format, you can do the following:

INSERT INTO Noticias VALUES 
(1, 'Texto da noticia', STR_TO_DATE('$date', '%d/%m/%Y'))
  • But in the database which should be the type of the date field?

  • Thank you very much! But it appears year/month/day, and I needed it to show day/month/year

Browser other questions tagged

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