I have a classified site… I’m trying to make a sql query that COUNTS the number of ads the user has posted in last 7 days, but I have a problem…
I’m trying to show in user profile something like this for example: [Username] has posted 30 ads in last 7 days
Here is my sql query ->
SELECT COUNT(*)
FROM table_name
WHERE user_id = '[user_id]' AND created_date > NOW() - INTERVAL 7 DAY
So in my case “table_name” contains ALL the ads from all the users and by “user_id = ‘[user_id]'” I show the user A his number of ads, and to USER B his number of ads etc…
So this query works, it counts the number of ads correctly, BUT, if for example user enters on site and DELETE’s 1,2 or whatever number of his ads, this number will be “minused” from the “[Username] has posted 30 ads in last 7 days”
- So let’s say for example user posted 20 ads in the last 5 days – The correct result is [Username] has posted 20 ads in last 7 days
- Now user enters on site and delete’s 4 ads – Now the result is [Username] has posted 16 ads in last 7 days
Can somebody help me please, what can I add to the query so the count still shows the correct number of ads (in my case 20 ads), even if the ads where deleted..
Thank you
Cheers
Instead of deleting a row using a
DELETE ... WHERE ...statement, add adeletedcolumn and use anUPDATEstatement:Then your counting function will work without modification.
Of course you will now have to fix all the rest of your code to not show deleted adverts. You can do this by adding
WHERE NOT deletedto all your other queries. You could also create a view that only shows ads that are not deleted and update your code to query this view instead of the original table.