4ndro1d
4ndro1d

Reputation: 2976

Cache data from MySQL in PHP?

Is it possible to ask for all data in my database and make objects from it and save it into an array or something, so I just need to call the database once and afterwards I just use my local array? If yes, how is it done?

public function getAllProjects(){

   $query="SELECT * FROM projects";
   $result=mysql_query($query);
   $num=mysql_numrows($result);
   while ($row = mysql_fetch_object($result)) {
      // save object into array
   }
}

public function fetchRow($row){
  include("Project.php");
  $project = new Project();

  $id=$row->id;
  $project->setId($id); 

  $title=$row->title;
  $project->setTitle($title);   

  $infos=$row->info;
  $project->setInfo($infos);

  $text=$row->text;
  $project->setText($text);

  $cate=$row->category;
  $project->setCategory($cate);

  return $project;
}

If I have for example this code. How do i store the objects correctly into an array, where I grab the data from? And why can't I make more than one object of type "Project"?

Upvotes: 1

Views: 289

Answers (2)

The Disintegrator
The Disintegrator

Reputation: 4187

Let's ignore the fact that you will run out of memory.

If you have everything in an array you will no longer have the functionalities of a relational database.
Try a search over a multi megabytes, multi dimensional array in php and be prepared for a extended coffee break. If you are thinking in doing something like that is because you feel that the database is slow... You should learn about data normalization and correct use of indexes then.
And no NoSQL is not the answer.
Sorry to pop your balloon.

Edited to add: What you CAN to is use memcache to store the final product of some expensive processes. Don't bother storing the result of trivial queries, the internal cache of mysql is very optimized for those.

Upvotes: 2

Weacked
Weacked

Reputation: 970

You should use the $_SESSION vars in php, To use them, add a session_start() at the beginning of your code. Then you can set vars with $_SESSION['selectaname'] = yourvar

Nothing prevent you to make a sql query like "SELECT username FROM users WHERE id = 1" and then set a $_SESSION['user'] = $queryresult

Then you'll have this :

echo $_SESSION['user'];

"mylogin"

Upvotes: 1

Related Questions