Justin
Justin

Reputation: 45350

Caching PHP variables for later use

What is the best way in PHP to do variable caching? For example, let's assume I have a table, with 4 rows.

         name |  job
--------------------------
 Justin Smith | Plumber
 Jack Sparrow | Carpenter
 Justin Smith | Plumber
  Katie White | Doctor

Which is built like:

foreach($people as $person) {
   echo $person->name;
   echo get_job($person->name);
}

And the function call get_job() looks like:

function get_job($name) {
  //This is pseudo code below
  $row = MySQL->Query("SELECT job FROM people WHERE name = $name");
  return $row->job;
}

As you can see, once we get the job of Justin Smith, further down we shouldn't and don't need to do a full MySQL query again, since we know it is Plumber.

I was thinking of doing a global variable which is a key=>value array like:

 global $jobs = array("Justin Smith" => "Plumber",
                      "Jack Sparrow" => "Carpenter",
                      "Katie White" => "Doctor");

Then in the get_job() function I simply just check if the name exists in the array before querying. If not, insert the name and job into the array and return the job.

Basically, is there a better way to do this that is more elegant?

Upvotes: 0

Views: 883

Answers (2)

pleasedontbelong
pleasedontbelong

Reputation: 20102

this is the typical n + 1 problem where you make 1 query to get the list of "person" and then you make one query for each person to get the "job".

Depending how they are related.. maybe you could get both using one single query. For example: if the relation is a Nx1 (1 person has 1 Job, and 1 job can be used for N Persons) then your initial query should be something like:

SELECT p.name, j.job FROM Person p INNER JOIN Job j ON (p.job_id = j.id) 

If the relation is a NxN, it gets tricky :P,

Hope this helps

Upvotes: 0

Plamen Nikolov
Plamen Nikolov

Reputation: 2733

There is many possible solutions. You can store the SQL result in an array that you can use on multipe places on the page. Instead of global you should use static:

 function get_job($name) 
 {
      static $people_jobs;

      if( !isset($people_jobs[$name]) || empty($people_jobs[$name]) )
      {
          $row = MySQL->Query("SELECT job FROM people WHERE name = $name");
          $people_jobs[$name] = $row->job;
      }

      return $people_jobs[$name];
}

This function will do a MySQL query only once for a person, no matter how many time you call get_job($name);

Upvotes: 1

Related Questions