Saturday, April 2, 2011

PHP-SQLUtils released

Yesterday, I created a project on github called PHP-SQLUtils. This is a small PHP library that helps make building SQL queries easier and less error-prone. I've been using a variant of this library at work and it has definitely come in handy. One thing that it can do is build INSERT statements.

In your typical INSERT statement, the list of column names come first, followed by the list of column values.
INSERT INTO cars
(make, model, year, purchased) VALUES
('Ford', 'Focus', 2005, '20050520 00:00:00')
It's a little hard to tell what values go with what columns. It gets harder as the list of columns gets longer.
INSERT INTO cars
(make, model, year, purchased, owner, seats, mpg_city, mpg_highway, color, sun_roof) VALUES
('Ford', 'Focus', 2005, '20050520 00:00:00', 'George Washington', 5, 30.4, 35.1, 'gray', 0)
PHP-SQLUtils provides an interface for building INSERT statements. It puts the column names right next to their values, making it easy to figure out what values belong to what columns and reducing the chance of a bug appearing:
$utils = new MssqlUtils();
$insert = $utils->insert("cars");
$insert->s("make", "Ford");
$insert->s("model", "Focus");
$insert->n("year", 2005);
$insert->d("purchased", strtotime("2005-05-20"));
echo $insert->done();
//prints "INSERT INTO cars (make, model, year, purchased)
//VALUES ('Ford', 'Focus', 2005, '20050520 00:00:00')"
Check out PHP-SQLUtils here.

No comments: