Insert current date into Database

1

I have a database with a News table with:

  • Id (Primary key and auto_increment)

  • News (varchar, where I write the news)

  • Date (where the current date should be, just dd / mm / yyyy)

But I never moved with dates and I do not know how to insert into DB with PHP .

Does anyone know anything about this that could help me?

    
asked by anonymous 12.07.2015 / 15:16

1 answer

2

In the database, I assume it is MYSQL, you can use the data type DATE to save 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 the INSERT using the CURDATE () 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 the 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 save in the format indicated, you can do the following:

INSERT INTO Noticias VALUES 
(1, 'Texto da noticia', STR_TO_DATE('$date', '%d/%m/%Y'))
    
12.07.2015 / 15:38