简体   繁体   English

发布计数器每日,每周,每月,所有时间php和mysql

[英]Post counter Daily,weekly,monthly,all time php & mysql

I got a website with several posts/articles which I can track by last 24h,last week,last month and all time views for each post. 我有一个网站,上面有几篇文章/文章,可以在过去24小时,上周,上个月以及每篇文章的所有时间浏览。

I save the timestamp on each view in the db. 我将时间戳保存在数据库中的每个视图上。 When someone opens the home page I loop these timestamps and save them accordingly to the last 24h/last week/last month/all time in the db. 当有人打开主页时,我循环这些时间戳,并将它们相应地保存到数据库中的最后24h /上周/上个月/所有时间。 This works "good" (but problem). 这工作“好”(但有问题)。

NOW THE PROBLEM: 现在的问题:

What if I have 5000 posts! 如果我有5000个帖子怎么办! the php script has to loop all 5000 posts and do the savings which is causing performance problems. php脚本必须循环所有5000个帖子并进行节省,这会导致性能问题。 The Site won't show up as soon the function is done. 该功能完成后,该站点将不会显示。 I already got an Error Message "Allowed memory size exhausted ...". 我已经收到一条错误消息“允许的内存大小用尽...”。

How can I solve this problem? 我怎么解决这个问题? Is there any solution. 有什么解决办法。

It's quite important to run this function on when open the home page to get the exact counter datas. 打开主页以获取确切的计数器数据时,运行此功能非常重要。

If I would do this function only on post view and then just for this post the datas wouldn't be accurate. 如果我只在发布视图上执行此功能,然后仅针对此发布,则数据将不准确。 Imagine the post has not been viewed for several days, the counter datas wouldn't be updated. 想象一下该帖子已经好几天没有被查看了,计数器数据不会被更新。

Note: It's for a Wordpress theme which isn't very important in this case. 注意:这是针对Wordpress主题的,在这种情况下不是很重要。

You could look into using WordPress's cron function wp_cron ( here ) 您可以研究使用WordPress的cron函数wp_cron在此处

NOTE: It does rely on access to fire, unlike a "true cron job". 注意:与“真正的cron工作”不同,它确实依赖火。

Also, look into using Transients API . 另外,研究使用Transients API Transients make a HUGE performance increase! 瞬态使性能大大提高! ( here ) 这里


The Transients API, in simple terms, caches a loop. 简单来说,Transients API会缓存一个循环。 So instead of cycling 5000 posts EVERY TIME, it will loop once then set some data. 因此,它不会每次循环5000个帖子,而是循环一次,然后设置一些数据。 On subsequent loads, it will fetch that cached data. 在随后的加载中,它将获取该缓存的数据。 If the data is NOT there or is EXPIRED, it will then loop the posts to cache new data. 如果数据不存在或已过期,则它将循环发布以缓存新数据。

Check out this psuedo-code 看看这个伪代码

if ( false === ( $query = get_transient( 'query' ) ) ) {
    // It wasn't there, so regenerate the data and save the transient
    $query = new WP_Query( '//Your Loop Stuff' );
    set_transient( 'query', $query );
}
$timestamps = $query->TIMESTAMP(or whatever you use);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM