-1

I have this website where I a user can create so many posts a day called 'clippets' and before I check the limit, I've used some SQL to get the total number of 'clippets' in the current day.

So let's say I only want to allow users to make 20 'clippets' a day, not based on time though only the day, as if I were to base it on the last 24 hours it would be like the user is chasing the limit all the time...

Anyway, here is my SQL:

$date = date("Y-m-d");

$sql = "SELECT COUNT(id) FROM clippets WHERE userID = ? AND DATE(createdAt) = '$date'; ";

My question is... Is this a slow way to approach this, using the PHP date function and then using that within the SQL query, does it treat them as strings or? Because the createdAt field is a datetime data type, so does MySQL convert both dates to strings and then compare? Is that a slow way of doing this?

Mohammed Alhanafi
  • 886
  • 1
  • 9
  • 22
Erdss4
  • 1,025
  • 3
  • 11
  • 31

2 Answers2

1

MySQL does not convert both dates to strings for the comparison. It converts the string to a date once, and uses that for all the other comparisons. Passing a date parameter as a string is standard practice and trying to do something else instead will not be a good source of optimization.

However, if you're only interested in the current date, you don't need to pass a parameter for the date at all. You can use MySQL date functions to select the rows you need. One of the approaches in this question or this question should work.

For example:

SELECT COUNT(id) FROM clippets WHERE userID = ? AND createdAt >= CURDATE()
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

As a rule, filtering on function results is slower than filtering on fields, particularly so with indexed field. If your datatype includes the time, your filter should resemble this:

where createdAt >= yourDateVariable
and createdAt < the day after yourDateVariable
Dan Bracuk
  • 20,699
  • 4
  • 26
  • 43