How to get only the date month with PHP from the database

Asked

Viewed 2,279 times

5

Well the date is in the format ( 2020-02-10 17:04:01 ) So I just want to take the month or day separately, the data is saved in the data Anco, I can get the whole date, but I wanted to take separately only the day and month. Here an excerpt from the code:

$query  = "SELECT * FROM barraswiki ORDER BY aprovam DESC, reg_data DESC"; 
$data = mysqli_query($dbc, $query);  
while($row = mysqli_fetch_array($data)){
$date = new DataTime($row['reg_data']);
$mes = data($date, 'd');
// code......
}

2 answers

6


Just do it in SQL, in case:

SELECT MONTH(reg_data) as mes, DAY(reg_data) as dia, barraswiki.* from barraswiki order by aprovam DESC, reg_data DESC;

But you can also format dates like this:

SELECT DATE_FORMAT(reg_data,'%d/%m/%Y') as data_brasil ...

To get the record in PHP get the alias:

$mes = $row['mes'];
$dia = $row['dia'];
  • Thanks friend, but there was a mistake there in SELECT, the table name is barraswiki. So how do I get the table data? above you put ( *.barraswiki ), however it gave error. Could correct friend, already wrong.

  • 1

    It was inverted, it was bad! >D

  • Gee, it worked perfectly :) You have no idea how you helped me, I was studying date a lot in PHP, and I learned a lot, but your help showed me that I should have focused on SQL. Thanks so much for the help! Stay with God.

6

If you only want to bring a specific field of a date record, you can use date functions like Day and Month, like explained here.

Example

SELECT MONTH(coluna_data) FROM suaTabela; /*seleciona apenas o mês*/

For your table, SELECT would look like this:

SELECT MONTH(reg_data), DAY(reg_data) from barraswiki order by aprovam DESC, reg_data DESC;

Already to select only one field from a date variable in PHP, you can use the function date(), as explained here.

Example

echo date('m',$variavelDeData); //Representação numérica de um mês, com zero à esquerda     
  • 1

    The friend up there already helped me, but thanks to you I have another very simple way to use, thanks friend! Thanks for the strength.

Browser other questions tagged

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