Does each of these mysql queries run each time the page is loaded?
In a config file which is included on every page of the script, I have the following code to fetch the preferred user's language file:
if ($_SESSION['id']) { // if logged in
$language = mysql_result(mysql_query("SELECT default_lang FROM employees WHERE id = '$_SESSION[id]'"), 0);
include "languages/".$language.".php";
} else { // If not logged in, use system default language
$language = mysql_result(mysql_query("SE开发者_如何学运维LECT config_value FROM system_config WHERE config_name = 'language'"), 0);
include "languages/".$language.".php";
}
My question is, does this query get run every single time the visitor refreshes a new page? What is the easiest way to see the total number of mysql queries on a given page- most often I see this in forums, etc. ie: 20 queries executed in XX sec.
Yes, one or the other will be run every time - which is a bit dumb since you've already done some per-user I/O to get the session - you could just....
$language=$_SESSION['lang'];
if (!$language) {
if ($_SESSION['id']) {
$language = mysql_result(mysql_query("SELECT default_lang FROM employees WHERE id = '$_SESSION[id]'"), 0);
} else {
$language = mysql_result(mysql_query("SELECT config_value FROM system_config WHERE config_name = 'language'"), 0);
}
$_SESSION['lang']=$language;
}
include "languages/".$language.".php";
Or even just use the 'Accept-Language' in the request (assuming you've used standard naming and have all languages)....
list($language)=explode(';', $_SERVER['Accept-Language']);
include "languages/".$language.".php";
(NB the code above using the request header would need to be cleaned up a bit to avoid local file inclusion vulns)
In general, it is a good idea to reduce the amount of queries, but I would rather keep the code clean early on. Caching will introduce all kinds of problems and unless you really need it because the query is slow, it's a waste of time that will increase the code complexity.
Simple queries that affect a single table and return a single value are quite fast. Chances are, your attempts to cache the value will not give a significant benefit.
To learn about performance, you should start using a profiler. It will show you what takes time in your scripts, and it probably won't be what you expect.
For development environments, I like XDebug with KCacheGrind. Here is an introduction tutorial: http://devzone.zend.com/article/2899
Yes one of the two queries will run every page load.
If you don't want this you can also put the default_lang variable in your SESSION.
Yes, it will be executed every time page is reloaded. However, technically, the second time it is faster since it picks up from cache or already has the query plan. Please anyone confirm if I am wrong?
精彩评论