将数据存储在全局/会话变量与MySQL查询中

时间:2022-12-10 16:57:29

A general PHP question about organizing a website: for efficiency purposes, is it better to store data from MySQL queries into global arrays, or to make a new query every time data is needed? I am thinking specifically of a sports stats-oriented website, with a lot of data that does not necessarily change very often. I have heard that storing the data into arrays is much more efficient, but I don't see how since global variables are only global in the scope of the current PHP page. Ideally, I'd like to populate all my arrays once I start my server. Should I use session variables then? I haven't heard of anybody doing that.

关于组织网站的一般PHP问题:为了提高效率,最好将MySQL查询中的数据存储到全局数组中,还是每次需要数据时都要进行新的查询?我正在考虑一个面向体育统计的网站,其中包含大量不一定经常变化的数据。我听说将数据存储到数组中要高效得多,但我不知道全局变量只是在当前PHP页面的范围内是全局的。理想情况下,我想在启动服务器后填充所有数组。我应该使用会话变量吗?我没有听说过有人那样做过。

1 个解决方案

#1


0  

Session variable won't resolve the issue, as the session is not global as well (unless you hack it by setting the same session_id to all visitors).

会话变量不会解决问题,因为会话也不是全局的(除非你通过为所有访问者设置相同的session_id来破解它)。

If you have a lot of traffic and you need to save queries, than use a cache server like memcached or redis.

如果您有大量流量并且需要保存查询,那么请使用memcached或redis之类的缓存服务器。

If you can't install memcached or redis, you can create a PHP file that contains the arrays, and include it in the scripts - e.g. use file caching. The bad thing about this approach is that you will use a lot of memory - the whole data should be read in the memory by any PHP script, by any visitor. So in case the database is not the bottleneck, better keep the queries.

如果无法安装memcached或redis,则可以创建包含数组的PHP文件,并将其包含在脚本中 - 例如使用文件缓存。这种方法的坏处是你将使用大量内存 - 任何访问者都应该通过任何PHP脚本在内存中读取整个数据。因此,如果数据库不是瓶颈,最好保留查询。

#1


0  

Session variable won't resolve the issue, as the session is not global as well (unless you hack it by setting the same session_id to all visitors).

会话变量不会解决问题,因为会话也不是全局的(除非你通过为所有访问者设置相同的session_id来破解它)。

If you have a lot of traffic and you need to save queries, than use a cache server like memcached or redis.

如果您有大量流量并且需要保存查询,那么请使用memcached或redis之类的缓存服务器。

If you can't install memcached or redis, you can create a PHP file that contains the arrays, and include it in the scripts - e.g. use file caching. The bad thing about this approach is that you will use a lot of memory - the whole data should be read in the memory by any PHP script, by any visitor. So in case the database is not the bottleneck, better keep the queries.

如果无法安装memcached或redis,则可以创建包含数组的PHP文件,并将其包含在脚本中 - 例如使用文件缓存。这种方法的坏处是你将使用大量内存 - 任何访问者都应该通过任何PHP脚本在内存中读取整个数据。因此,如果数据库不是瓶颈,最好保留查询。