views:

22

answers:

1

Hello, I'm currently attempting to implement APC caching as a datastore in my web application.

Currently, the system retrieves data directly from the MySQL database, and requires a database call per request.

I'm currently attempting to change this by prepopulating the cache with data which is intercepted and served from the cache at each request.

Here's the current method:

if(!empty($_GET['id'])){        

        $app = $db->real_escape_string($_GET['id']);
        $result = $db->query("SELECT * FROM pages_content WHERE id = $app");
        $rawdata = $result->fetch_assoc();

}

Data is presented by output by:

$title = stripslashes($rawdata['title']);
$meta['keywords'] = stripslashes($rawdata['htmlkeywords']);
$meta['description'] = stripslashes($rawdata['htmldesc']);
$subs = stripslashes($rawdata['subs']);
$pagecontent = "<article>".stripslashes($rawdata['content'])."</article>";

What I need the prepopulating script to do is for each row of data in the data table, cache each row's data. The serving script would then be able to pluck the data from the cache as an when required, using something such as apc_fetch('[columname][id]').

How could I devise this?

I assume I'd need to serialize the data?

+1  A: 

I really don't know you cache schema so the reply can't be exact. First: remember that APC uses the server's shared memory, in which case if you have multiple server they all will fetch at least once the db to get the data. If you try to store per column you need to be sure of create some sort of lock otherwise you will be having race conditions since maybe when you are saving a column any other could change. What I recommend you is to save the row completely, just doing:

<?php
foreach ($row = $mylsql->get_row()) {
  $key = 'content_' . $row['id'];
  apc_store($key, $row);
}

But in the other hand that means if you have 1000 articles you will save them in the cache and maybe many of them are not read at all.

Int that case I would recommend you use lazy loading:

<?php
$id = $_GET['id'];
$key = 'content_' . $id; 
$data = apc_fetch($key);
if (!is_array($data)) {
  // call mysql here
  $data = $mylsql->get_row();
  apc_store($key, $data);

}

// your script here using $data

this way you only cache the content that is often hit.

In the other hand please be consistent with your cache invalidation, to avoid having old data in the cache.

Gabriel Sosa
If I try to use this, I recieve error: Cannot use object of type mysqli_result as array. Using code:`foreach ($row = $db->query("SELECT * FROM pages_content") as $key){ $key = 'content_' . $row['id']; apc_store($key, $row);}`
Shamil