Capture Month in date field

1

I have a date field 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 make 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 did not work .... Does anyone know the correct way to perform this action?

    
asked by anonymous 04.11.2015 / 23:59

1 answer

1

Use the month () MySQL to compare only the month with the desired value. There are other functions to extract a piece of date as 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 not we use functions of type mysql_ *?

MySQL vs PDO - Which is the most recommended to use?

How to prevent SQL injection in my PHP code

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

    
05.11.2015 / 00:06