0

I need to query data in order to display number of registered users for each day of the current month, in order to pass json array to jQuery Flot.

This is what I have so far:

      for ($i = 1; $i <= date('t'); $i++) {
          $date = date('Y') . '-' . date('m') . '-' . $i;
          $sql = $db->first("SELECT COUNT(*) AS total FROM users WHERE (DATE(created) = '" . $date . "' LIMIT 1) GROUP BY DAY(created)");

          ($sql) ? $jdata['regs']['data'][] = array($i, (int)$sql->total) : $jdata['regs']['data'][] = array($i, 0);
          $jdata['xaxis'][] = array($i, date('j', strtotime($date)));
      }

      print json_encode($jdata);

The above works fine, except that it makes 30 queries due to the for loop. I would like to be able to optimize it, by eliminating for loop and use it on $sql array instead.

1
  • I guess you can do that with only one query, grouping by day. Something link SELECT day(created), COUNT(*) FROM users GROUP BY day(created); Commented Apr 19, 2015 at 1:55

1 Answer 1

1

You can try this way to get number of registered users for each day of the current month using BETWEEN clause . Let me know it's works for you or not.

SELECT DATE(created),COUNT(id) as total
FROM users
WHERE DATE(created) BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 1 MONTH)  
GROUP BY DATE(created)
Sign up to request clarification or add additional context in comments.

2 Comments

INTERVAL 30 DAY will not work, since some months have more than 30 days.
The interval should be between 1 and 31. Anyway, I think it would be easier to calculate the interval in php and pass it as a parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.