PHP – Saving Database Queries
Posted May 18th, 2009 by Conor in in Languages,PHPThis is something I wrote today while building botb SNS – a project that I will have to start blogging about soon! It should be used on large scale projects that have multiple database queries. It will be very useful if you have so many queries that you can’t keep track of them and are afraid of re-querying incidentally. Enough said – down to the code:
<?php
class user{
var $id;
var $name='';
var $username='';
var $email='';
function __construct($id){
$this->id=$id;
}
function about($t){
if($this->$t!=”) return $this->$t;
$q=dbRow(‘select ‘.$t.’ from users where id=”‘.$this->id.’”‘);
$this->$t=$q[$t];
return $this->$t;
}
}
?>
You will obviously have to adjust this to suit your database setup. It also requires the following function:
function dbRow($q){
$s=mysql_query($q);
$r=mysql_fetch_assoc($s);
return $r;
}
As you can probably see this example simply echos database information. The main benefit of the class is it will never make the same query twice. Once you ask for the username it is stored within the class so if you ask for it again in the same page it doesn’t have to query the database again. You could look at it as a type of internal page caching. Also it is incredibly easy to use. All you need to do is:
$u=new user($id);
echo 'Query Database: '.$u->about('name');
echo '<br/> From Memory: '.$u->about('name');
Easy as that!