phpMyDB – Data base class for MySql
phpMyDB is not only a class handler for MySql written in PHP, it’s also has a query cache built in, a great debugger and is damn easy to use!
I’ve wrote this class just few weeks a go since I need it for the new version of Open Classifieds (coming soon I promise, many changes).
This class uses fileCache class to be able (if you want to) to cache the query result in a really simple way (transparent to the programmer).
First Download
Usage with examples:
Constructor:
DB Constructor – connects to the server and selects a database
$ocdb = new phpMyDB(DB_USER, DB_PASS, DB_NAME,DB_HOST,DB_CHARSET);
In case of error will print using the private function print_error
Debugger:
Logs all the connection or action inside the class, you can set it on whenever you want.
$ocdb->setDebug(true); $ocdb->returnDebug();
We set it on, and at the end of our script(or whenever you want) we should returnDebug, by default in “HTML”, but can return as an “array”.
Also you can add new “logs” with $ocdb->addLog(“any string”);
Activate cache:
Uses fileCache class. As parameter we have:
1: true or false to activate or deactivate the cache, by default false
2: Time in seconds by default 3600 (10 seconds expires in the example)
3: Path for the cache, by default cache/
$ocdb->setCache(true,10);
Normal query:
Just performs a normal query, but keeps the query counter and logs the action if debugger it’s on
$result =$ocdb->query($query); if (mysql_num_rows($result)){ while ($row=mysql_fetch_assoc($result)){ echo $row['title']; } }
getRows
Returns in rows the target query. If cache is activated automatically cache the result as an array.
Parameters:
1: Query to return values
2: Returning as “assoc” (default), “row” , “object” ,”value” (returns first field form the query)
3: Cache type “cache” or “APP” by default “cache”
Example: Cached query, returning the row as an object (cache must be activated):
$result=$ocdb->getRows($query,"object"); if ($result){//more than 1 result foreach ( $result as $row ){ echo $row->title; } }
getValue
Get value from first value of the query and stores it in the cache.
$query="SELECT count(*) total FROM oc_postshits"; $total_records = $ocdb->getValue($query,"APP");
In the second parameter we can use “cache” (default).
Insert:
Insert into,parameters:
1: table + fields
2: values
$ocdb->insert("categories (name,friendlyName)","'name','fname'");
To get the last id use $ocdb->getLastID();
Update:
Updates table, parameters:
1: table
2: sets
3: where
$ocdb->update("posts","isAvailable=0,isConfirmed=0","idPost=1 and password='asdsadsad'");
Delete:
Delete from, parameters:
1: table
2: where
$ocdb->delete("categories","idCategory=2");
Close db:
Closes DB connection and unsets variables.
$ocdb->closeDB();
Full example:
include "phpMyDB.php"; define('DB_HOST','localhost'); define('DB_USER','user'); define('DB_PASS','some pass'); define('DB_NAME','openclassifieds'); define('DB_CHARSET','utf8'); $ocdb = new phpMyDB(DB_USER, DB_PASS, DB_NAME,DB_HOST,DB_CHARSET); $ocdb->setDebug(true); $ocdb->setCache(true,10); $ocdb->insert("postshits (idPost,ip)","97,'10.0.0.0'"); echo 'test insert see id:' . $ocdb->getLastID(); $query="SELECT count(*) total FROM oc_posts"; $total_records = $ocdb->getValue($query,"APP"); echo 'Total records: '.$total_records; $query="SELECT p.title from oc_posts p Limit 3"; $ocdb->setCache(false);//cache deactivated $result=$ocdb->getRows($query,"object"); $ocdb->setCache(true);//after the query is done activated once more if ($result){//more than 1 result foreach ( $result as $row ){ echo $row['title']; } }//if count else echo "nothing found"; $ocdb->closeDB(); $ocdb->returnDebug(); echo $ocdb->getQueryCounter().' queries generated and '.$ocdb->getQueryCounter("cache").' queries cached';
A DB class that records the execution time of every query is a good idea but here are some improvements that I think are important:
- Charset definition on the constructor: When you are dealing with UTF-8 data on MySQL servers with default latin1 charset is important to use mysql_query(“SET CHARACTER SET utf8″,$link); if you don’t want to mess up the data.
- Array parameters: It would be great to just put something like $ocdb->insert(‘tablename’,array(‘field1′ => ‘value1′,’field2′ => ‘value2′); or $ocbd->select(‘tablename’,array(‘id’ => 5));
- Get rid of mysql_num_rows: I’m not sure but I think it’s a performance killer, anyway, you don’t need to call that function, you can just call mysql_fetch_* and see if it returns false.
- Implement a method to get the row count: Something like $ocbd->numregs. A good way to do it is SQL_CALC_FOUND_ROWS
The charset!! uau that I absolutely forgot damn! xD
About the array to insert is good idea as well.
mysql_num_rows: I’ll let the user choose, I don’t use num_rows
Really interesting the SQL_CALC_FOUND_ROWS, I’ll take a look.
Thanks for this, I hope it’s use full this class, I’m using it not yet in production but I’m doing few tests and works fine until now
You will release a new version soon ?
I think I will start to develop websites based on your class (phpMyDB+fileCache). I’ve tested this class and really like it.
Keep up the good work!
Let me know, Thanks!
Hello Alex,
They maybe be small changes but not major releases and tha API will remain the same ;)
Sorry alex, we actually did a new release just that I forgot to publish it :S sorry
phpMyDB source:
http://openclassifieds.googlecode.com/svn/branches/172/includes/classes/phpMyDB.php
And you will need:
Wrapper cache:
http://openclassifieds.googlecode.com/svn/branches/172/includes/classes/wrapperCache.php
fileCache:
http://openclassifieds.googlecode.com/svn/branches/172/includes/classes/fileCache.php
usage example:
http://code.google.com/p/openclassifieds/source/browse/branches/172/includes/controller.php
I have implemented the classes with one website but I can’t figure how to modify the cache expiry time.
exemple:
$query=”select * from cat”;
$result=$ocdb->query($query);
//how can i set a different cache only for this query using the latest version of phpmydb(including Wrapper cache and filecache)?
I’ve tried using :
$query=”select * from cat”;
$ocdb->setCache(true,30);// 30 seconds
$result=$ocdb->query($query);
with no luck.
Also the function deleteCache(15); //older than 15seconds
is not working, it erases all cache.
set cache erases all the cache.
you can change the cache just for that query by changing the method at the wrapper cache documentation here: http://neo22s.com/wrappercache/
If you suggest to use:
$cache = wrapperCache::GetInstance(‘filecache’,36,’cache/’);
$query=”select * from cat”;
$result=$ocdb->getRows($query);
//cache for 36 sec
wrapperCache::GetInstance(‘filecache’,60,’cache/’);
$query1=”select * from cat”;
$result1=$ocdb->getRows($query1);
//cache for 60 sec
is not working, will cache both query’s for 36 seconds.
can you give us an example with that method?
Again, I use the last version of phpmydb(including Wrapper cache and filecache).
Thank you !
aha! now I understan you!
you need to do the setter getter for this variable $this->cache_expire
then do something like $cache->setExpireTime(30); for example the function you need to create it ;)
I thought that the function already exist.
It’s beyond my capabilities to create this function, even if I will manage to create it, for me this is extremely difficult to implement this in your class especially that there are 3 files.
Please let me know when you will release a new version including this fetaure because will be good for pagination with cache set to expire at 1 minute interval.
Thank you!