I´m currently using this code for outputting an array of results:
<?PHP
$db = JFactory::getDbo();
//Start date
$startdate = date('2010-05-21');
// End date
$end_date = date("Y-m-d");
$arraystring = '';
while (strtotime($startdate) <= strtotime($end_date)) {
$query = "SELECT * FROM table1 WHERE FROM_UNIXTIME(tm,'%Y-%m-%d') = '".$startdate."'";
$db->setQuery($query);
$replyAGS = $db->query();
$my_count = $db->getNumRows();
$arraystring .= $my_count.', ';
$startdate = date ("Y-m-d", strtotime("+1 day", strtotime($startdate)));
}
$arraystring = rtrim($arraystring, ', ');
?>
As you can see I´m doing a database query inside a loop running from a specific date up until current date. Let´s say that this loop was running from jan. 2007 to jan. 2014 that would mean a total loops of 2557, would this not be a serious problem regarding performance / server load?? Is there a smarter way to do this?
I am guessing the final implementation but I would suggest
First getting all the records that you want (You can customize the query to give you lesser records).
When you loop the $result
This way you can get the count in a array grouped by the timestamp.
Then you need to sort it so that it is ascending order
Then you loop the array to get the date
You also do
Is this what you want ?
Please try with this query:
If it work for you you have to add:
You can change your query to the following:
SELECT * FROM table1 WHERE FROM_UNIXTIME(tm) BETWEEN '" . $startdate . "' AND '" . $end_date . "'
. This will select all results that are within your provided timespan.Next, you'll want to loop through the results and count the amount of results per day, like so:
Then finally in your existing while-loop you can do
$my_count = (isset($counts[$result['tm']])) ? $counts[$result['tm']] : 0;
to access the amount of results for the given day.This results in:
And you now have the same functionality with only 1 query.
Next, I'd probably move the counting code into its own function, like so:
Hope this helps.
I finally did it! And I think this is a reasonable solution without putting too much strain on the server ressources.
Please have a look and see if it´s ok regarding performance. Note that I am using a foreach loop inside the while loop, but at least now I´m not quering MySQL in each loop..
EDIT
Here is an optimized code i made where I only do one database query and one loop. I use a smart detection inside loop to check for missing results per day and if needed I fill the array with zero values. Look here: