PHP Database Library
For a while now, I’ve been working on a PHP DB wrapper class. The whole point of it is to make writing the same old queries over and over again a little bit easier to manage. I’ve noticed that I haven’t had to edit it over the past few months, and I’ve implemented it at work without issue on many occasions, so I figure it’s time to share it with the world.
To use it, first create an instance of the object:
$db = new db("user", "pass", "db", "host");
And once you have it, you can perform various types of queries.
For selects that will return multiple rows, use the following syntax:
$rows = $db->q("SELECT * FROM tbSomeTable;");
$rows will then either be false (which means the record had an error or returned 0 records) or an array of row objects:
foreach($rows as $row){
print($row->someField);
}
For single-row queries (such as those with LIMIT 1 or using a COUNT or similar function), use sq:
$row = $db->sq("SELECT COUNT(*) AS intCount FROM tbSomeTable;");
$row is then an object representing a single row of the resultset. If the query returns multiple rows, only the first row is used.
For insert, update, delete, and other queries, $db->q is used.
An advantage to my wrapper is the printf-like auto-escaping, allowing you to easily use user input:
$rows = $db->q("SELECT * FROM tbUsers WHERE User='%s' AND Pass='%s';", $_POST["user"], $_POST["pass"]);
The %s are then replaced with the corresponding argument and automatically stripped using mysqli’s strip function.
Here’s a short snippet tying everything together showing how quick and easy it is to write a DB resultset iteration:
if(($rows = $db->q("SELECT * FROM tbUsers WHERE intUserType='%s';", $_GET["intUserType"])) !== false){
foreach($rows as $row){
print($row->strUsername . “<br />”);
}
}else{
print(”No records found!”);
}
Debugging can be achieved via $db->messages();
It also has support for transactions (commit, rollback), documented in the readme
If you want to give it a try, you can download it here
If you have any questions or suggestions, leave them in my comments!





Leave a comment