I'm trying to create a blog system with php and I need a way of counting the most viewed post during the last 21 days. Does anybody know of a good way of doing this?
I don't have much experience with php so i need someone to point me in the right direction. I have tried to look into google anlytics API but it seems a bit complicated. Would it be easier to just use cookies?
Since you are building your own blog system, here is the simplest way to do it:
I assume that this is anonymous counting of your blog post visits. If you want to have ip logged records you'll have to adjust the business logic.
Create a new table called visits.
Add an id (Primary key), a field called blogpostid ( that will store the id of the post being viewed) and a field called dtpost with timestamp or datetime properties that upon insert will automatically put the date/time.
Now you can query like this:
select visits.blogpostid, count(dtpost) as counted from posts
left join posts on posts.id = visits.blogpostid
where dtpost between (NOW() AND <-21 days interval function>)
order by counted DESC group by visits.blogpostid;
What you really do is storing the datetime of someone visiting your blog post. This automatically is a count so whatever interval you put the between will fetch the data *. Then the count() function does the counting.
One thing to know is that your own browser refresh will add up to the counting of the visits so you'll have to provide a way to block counting the refresh of the browser (usually a time limit or a cookie to say that you have already seen that page).
*Edit:
Since this is ambiguous, what I mean is that it will fetch your data within the time period that you want.
Create a table views with a foreign key to post ids and add an entry with the visitors information and the date. Then you can fetch the most viewed posts like this (untested):
SELECT p.*, COUNT(p.*) count FROM posts p
INNER JOIN views v ON v.post_id = p.id
WHERE DATE_SUB(CURDATE(), INTERVAL 21 DAY) <= p.date_viewed
ORDER BY count DESC
GROUP BY p.id;
To prevent the count from incrementing when viewed multiple times by the same user you can use the session meganism to prevent that from happening.
session_start();
if (!isset($_SESSION['posts_viewed'])) {
$_SESSION['posts_viewed'] = array();
}
// some logic to get to relevant post id here
// check that the post_id is not in the array
if (!in_array($post_id, $_SESSION['posts_viewed'])) {
// logic to increment a persistent counter (e.g. in mysql) here
// add post_id to array
array_push($_SESSION['posts_viewed'], $post_id);
}
// finally some logic that display the post here
session_close();
Related
I have a screen that looks very much like facebook timeline
users can view posts of other users etc.
to get these posts i do something like
select user.id,user.name,posts.title,posts.body from posts left join users;
now data i need to collect is "Who saw this post" .
is there any elegant way to do it ?
right now all what i can think of is every time i fetch posts. i loop over them, then collect all ids of posts that the query returned and then push in another table
user_views [pk:user_id+postId]
userId,postId
1 , 1
Then when i'm fetching posts next time i can do count of user_views.
select *,count(user_views.id) from posts join user_views on post_id = post.id
but this sound like a lot of work for each VIEW, specially that most probably user will see a most multiple times,
is there any known patterns for such need ?
This is a design question and the answer really depends on your needs.
If you want to know exactly who viewed what post and how many times, then you need to collect the data on user - post level.
However, you may decide that you do not really care who viewed which post how many times, you just want to know how many times a post was viewed. In this case you may only have a table with post id and view count fields and you just increment the view count every time a post is being viewed.
Obviously, you can apply a mixed approach and have a detailed user - post table (perhaps even with timestamp) and have an aggregate table with post id and view count fields. The detailed table can be used to analyse your user's behaviour in a greater detail, or present them a track of their own activities, while your aggretage table can be used to quickly fetch overall view counts for a post. The aggregate table can be updated by a trigger.
I have a website where people can make posts and follow other users. I have a sidebar that has a value that keeps track of the number of posts that have been posted since your last visit.
I'm stuck thinking of how I should handle this. Should I create an entirely new table in the database called notifications that would hold the user's id and the number of posts since last visit, should I just add a column in the existing user table for this value, or should I use an entirely different method?
Thanks.
First of all: Think, which object this is a property of. In your case, the count will differ from user to user, so we might assume, it is a user property.
We could hang it on the last login, but this would give us a wrong count, if the user is logged in for a long period (The user doesn't want to know the count since his last login, but since his last activity!).
So the easiest way could be to add a field to the users table, that holds the last post ID - We just SELECT MAX(id) FROM posts and update users.lastSeenPost with the result on every user action. We can then display MAX(post.id)-users.lastSeenPost as the new post count.
Every post has a date recording when it was made.
Every user will have a date keeping track of when he/she logged in the last time.
By the following SQL statement you could ask the database to return the number of posts since the user logged in last:
SELECT COUNT(*) FROM `posts` WHERE `posts.post_date` > `user.lastlogin_date`
I suggest that you will create a cookie ($_COOKIE['lastPostId']) in each customer webbrowser with the LAST ID of your posts, and, when the user return, you will read $_COOKIE['lastPostId'] and query your database as SELECT * FROM posts WHERE id>lastPostId
I am working on a social network website project. I have created database and everything.
The posts table has a preference column which stores the preference value according to the likes and comments that a post gets from the users and also the time at which the post is created.
To retrieve posts for a user's home page from the posts table, I am running a query using joins which sorts using preference column .
Now, suppose I retrieve 10 posts for a user to be shown on the posts table and user scrolls down and one more request is made from the user to retrieve next 10 posts to the server.
If in between of those requests few other users creates a new post or preference value of posts in the database changes in the between, and now if I the second request is run on the server, all the posts will be resorted for the second request (i.e. to show next 10 posts) but since the database is updated , this means in the second request there will be many chances that few of earlier 10 posts are retrieved along in the second request.
I want to know how to avoid these duplicate requests.
How facebook or any other social network solves this problem at the backend when their database is dynamic.
I would rather avoid such unreliable way of sorting at all.
As a user, I'd rather quit that service. Frankly, I hate such too smart a service which decides which posts I have to see and which not. And even dynamically ordered on top of that.
Make it ordered by date, by tags of interest, by something sensible, reliable and constant.
In your script store a record of the rows id returned.
For example, using a basic limit and just storing the latest id when the first select is done, and using the page number to determine the limit of records to return.
SELECT id, somefield
FROM SomeTable
WHERE id < $SOMESTOREDVALUE
LIMIT $PAGENUMBERTIMESTEN, 10
or storing the latest id after each page is returned (which you will need to store each time this is run)
SELECT id, somefield
FROM SomeTable
WHERE id < $SOMESTOREDVALUE
LIMIT 0, 10
If you store the time & date when the user first makes a request in a session, you could use that to filter the posts table.
So your SQL for the second page of results would be along the lines of
SELECT <some fields> FROM <sometables>
WHERE DatePosted <= $timefirstseen LIMIT 10, 10
Where $timefirstseen was loaded from the session variable. This will restrict your results to only posts that existed when the users visit started.
You would of course need to include a feature to allow the user to clear the session or do that automatically when they revisit their homepage to make sure they got to see the new posts eventually!
I'm trying to create a filter to show certain records that are considered 'trending'. So the idea is to select records that are voted heavily upon but not list them in descending order from most voted to least voted. This is so a user can browse and have a chance to see all links, not just the ones that are at the top. What do you recommend would be the best way to do this? I'm lost as to how I would create a random assortment of trending links, but not have them repeat as a user goes from page to page. Any suggestions? Let me know if any of this is unclear, thanks!
This response assumes you are tracking up votes in a child table on a per row basis for each vote, rather than just +1'ing a counter on the specific item.
Determine the time frame you care about the trending topics. Maybe 1 hour would be good?
Then run a query to determine which item has the highest number of votes in the last hour. Order by this count and you will have a continually updating most upvoted list of items.
SELECT items.name, item_votes.item_count FROM items
INNER JOIN
(
SELECT item_id, COUNT(item_id) AS item_count
FROM item_votes
WHERE date >= dateAdd(hh, -1, getDate()) AND
## only count upvotes, not downvotes
item_vote > 0
group by item_id
) AS item_votes ON item_votes.item_id = items.item_id
ORDER BY item_votes.item_count DESC
You're mentioning that you don't want to repeat items over several pages which means that you can't get random ordering per request. You'll instead need to retrieve the items, order them, and persist them in either a server-wide or session-specific cache.
A server-wide cache would need to be updated every once in a while, a time interval you'll need to define. Users switching page when this update occurs will see their items scrambled.
A session-specific cache would maintain the items as long as the user browses your website, which means that the items would be outdated if your users never leave. Once again, you'll need to determine a time interval to enforce updates.
I'm thinking that you need a versioned list. You could do the server-wide cache solution, and give it an version (date, integer, anything). You need pass this version around when browsing the latest trends, and the user will keep viewing the same list. Clicking on the Trends menu link will send them to the browsing pages without version information, which should grab the latest from your cache. You then keep this as long as the user is browsing these pages.
I can't get into sql statements, not because they are hard, but we don't know your database structure. Do you keep track of individual votes in a separate table? Are they just aggregated into a single column?
Maybe create a new column to record how many views it has? Then update it every time someone views it and order by threads with the largest number of views.
i already created a table for comments but i want to add the feature of thumb Up and Down for comments like Digg and Youtube, i use php & mysql and i'm wondering What's the best table scheme to implement that so comments with many likes will be on the top.
This is my current comments table : comments(id,user,article,comment,stamp)
Note: Only registred will be able to vote so it should limit 1 vote to each user in a comment
Thanks
Keep a votes table. E.g. votes(comment_id, user_id, value, stamp) - value is -1 or +1.
This allows accountability, and you can do a UNIQUE index on (comment_id, user_id) to prevent duplicate voting. You can also remove a user and all of his votes easily, if he/she is spamming.
For sorting comments by score it is possible to do a JOIN between the comment and vote tables and use SUM/GROUP BY to get the total score. However, this can be slow. For speed, you might consider keeping a score field in the comments table as well. Every time a new row is added to the votes table, you add/subtract 1 from the comment's score.
Because you are storing every vote in a table, it is easy to recalculate the score on demand. Stack Overflow does something similar with reputation - the total reputation score for a user is cached and recalculated every so often.
You could add a score field and increment or decrement with each thumb action:
UPDATE comments SET score=score+1 Where id=123
Then when you select, order by score DESC.
Since a user should be registered to thumb up/down, I would store the user ID and the post ID to validate the up/downs.
2 tables will be appropriate for this task. Let me know if you need a design.