I’m trying to collect a sum of numbers from multiple rows like so:
(Simplified version to isolate the problem)
"SELECT sum( field_voeding_vlees_value )
FROM content_field_date
LEFT JOIN content_type_expense ON content_field_date.nid = content_type_expense.nid
WHERE addtime( str_to_date( field_date_value, '%Y-%m-%dT%k:%i:%s' ) , '01:00:00' ) >= '2011-11-01'
AND addtime( str_to_date( field_date_value, '%Y-%m-%dT%k:%i:%s' ) , '01:00:00' ) <= '2011-11-31'"
This query works perfectly in phpMyAdmin, returns something like:
sum(field_voeding_vlees_value)
115.12
However, when I run it in a php-script(in a custom module in drupal) with this code:
$result_query_totals = db_query("SELECT sum( field_voeding_vlees_value )
FROM content_field_date
LEFT JOIN content_type_expense ON content_field_date.nid = content_type_expense.nid
WHERE addtime( str_to_date( field_date_value, '%Y-%m-%dT%k:%i:%s' ) , '01:00:00' ) >= '2011-11-01'
AND addtime( str_to_date( field_date_value, '%Y-%m-%dT%k:%i:%s' ) , '01:00:00' ) <= '2011-11-31'");
$row = mysqli_fetch_object($result_query_totals);
print_r($row);
This outputs:
stdClass Object
(
[sum( field_voeding_vlees_value )] =>
)
Also tried selecting normal values, problem persists, however if I remove the WHERE part which filters on the dates(strings transformed to dates tbh) the query works fine?
Thoughts?
You need to escape the
%marks in your query,db_query()uses%as a placeholder marker and performs a string replacement on things like%s,%d,%b, etc. They’re escaped using a double percent (%%):