views:

485

answers:

5

My AJAX search program keeps asking PHP for results of a particular search term. The start of the PHP script reads thru a MySQL DB and initializes, so if the PHP keeps restarting, it will have to read the DB millions of times. If I can keep it alive and let multiple silly AJAX requests be served by a single running PHP script instance I'm sure performance would improve.

How do you do this typically? Use a service? Can this be done with services?

+1  A: 

If you know the results are the same every time, just move those results to a session variable.

PHP sessions are explained pretty well in their documentation:

http://us3.php.net/manual/en/book.session.php

Anthony
+1  A: 

How about storing the db results in a session variable? You'd check first if the keyword is not in the session (sessions allow to transport variable values between page refreshes), and if not, do a db query.

To store it:

$_SESSION['storedQueries']['keyword']= 'its definition, from the database';

To look for it:

  $index=  array_search('keyword',array_keys($_SESSION['storedQueries']));
  $result = ($index) ? $_SESSION['storedQueries'][$index] : 'nothing found, you should do a db query';

The ajax part is pretty easy if you use a javascript library, such as jquery:

$('#resultZone').load('find.php',{keyword: $('input.search').val() });
pixeline
Are session variables sent on HTTP?
Jenko
from the doc: " A visitor accessing your web site is assigned a unique id, the so-called session id. This is either stored in a cookie on the user side or is propagated in the URL. "
pixeline
+2  A: 

PHP has no concept of long-lived objects or shared state between threads or requests, every request always starts at zero (except for the session state, of course). You can emulate long-lived objects by caching to disk or memory (see memcached).

Do you have a particular reason to read the entire database when your script initializes?

Henning
+1  A: 

If the search result is something that would be similar to multiple users, I usually create a cache file and serialize the result set there. As a filename I might use md5sum of a string containing the search query and perhaps user group. Then when a Ajax needs the data I just need to check if the file is too old, if not I just need to send it to the client or maybe even just redirect the Ajax http-request to the file (assuming it is formatted properly). If the file is too old, I just refresh it with new content.

For very high volume sites memcached is usually a better option. And also some kind of php cache helps and SQL connection pooling lowers the overhead of opening SQL connections.

Raynet
A: 

connecting to the DB is a very expensive operation and you can go around that by caching the results, take a look at Zend_Cache and see how it can save you allot headache.

Shreef