David Cramer's Blog


This afternoon I posted my PHP database library on Google code. It's designed to be very lightweight, and uses the PHP4 MySQL functions as well as the PostgreSQL functions, but is built for PHP5. It uses sprintf formatting, and works must like the Python database cursor's, to help alleviate injection concerns while you are writing your SQL queries. It also uses lazy connections, so you don't need to worry about connecting to your database when you won't be executing any statements.

For example:

// initiate connection
$db = new MySQLdb('localhost', 'root', 'mysupersecretpassword', false, 'database_name');
// query something useless
$query = $db->query('SELECT 1 FROM mytable WHERE value = %s', true);
$result = $db->fetch-array($query);
$value = $result[0]
// or alternatively
$result = $db->query_result('SELECT 1 FROM mytable WHERE value = %s LIMIT 1', true);
$value = $result[0]
// or even more of a shortcut
$value = $db->query_result_single('SELECT 1 FROM mytable WHERE value = %s LIMIT 1', true);
It automatically converts arguments including booleans, strings, integers, and null values, to their appropriate data type in MySQL, and will quote the data if nescesary. It also automatically runs proper escapes on any data.
$db->query("SELECT 1 FROM mytable WHERE bool_value = %s AND null_value = %s AND string_value = %s AND int_value = %s", true, null, 'hello', 1);

If someone wishes to force me to learn the mysqli_ functions, feel free to send me the changes to the library and I will gladly implement them. Also, I'm aware that PDO and other extensions exist, but a database library isn't complicated. When deploying code on many servers, it's much easier to have things present in the code base, than to require on external dependencies.

Hope this is useful!