Capture Month in field date

Asked

Viewed 809 times

1

I have a field date in my Mysql database and it stores the date of type y-m-d which is already used in other queries, but now I need to capture only the month to perform a sum.

The code I have is this

date_default_timezone_set('America/Sao_Paulo');
        $datamensal = date('m-d');
        $stw = mysql_query("SELECT SUM(valortotal) as total_mensal FROM pedidos WHERE data = '$datamensal'");

But it didn’t work.... Does anyone know the right way to carry out this action?

1 answer

1

Use the function Month() Mysql to compare only the month to the desired value. There are other functions to extract a piece of the date like year(), day() etc..

select month(now()) #retorna 11

or

$datamensal = date('m');
$stw = mysql_query("SELECT SUM(valortotal) as total_mensal FROM pedidos 
                    WHERE month(data) = '$datamensal' AND year(data) = year(now())")
       or die(mysql_error());

while($row = mysql_fetch_assoc($stw)){
   echo $row['total_mensal'] .'<br>';
}

Recommended reading:

Why should we not use mysql type functions_*?

Mysqli vs PDO - which is the most recommended to use?

How to prevent SQL code injection into my PHP code

Why parameterized SQL queries (name = ?) prevent SQL Injection?

  • But then type, in this case it returns equal to 11 which function I use to capture the current date of my computer and make the comparison.

  • @Alfredolima you are already using the date() php, just ask for the month for it. instead of m-d

  • Okay, I get it, check for me. &#xA;date_default_timezone_set('America/Sao_Paulo');&#xA; $datamensal = date('m');&#xA; $stw = mysql_query("SELECT SUM(valortotal) as total_mensal FROM pedidos &#xA; WHERE month(data) = '$datamensal'");

  • It is to be that @Alfredolima, will add up all the records of the month of November, it is good to specify the year tbm ;), you do not want to add up the records of previous years. I’ll edit the answer.

  • I did it the way you said, but it didn’t work, it doesn’t display anything.

  • @Alfredolima, with the year() stopped working or was already right? appeared some error?

  • No it was no longer working, no mistakes.

  • @Alfredolima decided not to forget to accept the answer :)

Show 4 more comments

Browser other questions tagged

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