A simple database utility for PHP

The following is inspired by the way old time web framework OpenACS does database access.

Before:

$rows = db_query_and_setup("SELECT email, name FROM email_addresses");
while ($row = mysql_fetch_array($rows)) {
  $email = $row[0];
  $name = $row[1];
  echo "$name : $email";
}

After:

$i = db_multi_row("SELECT email, name FROM email_addresses");
while ($i.next()) echo "$name : $email";

(The function db_query_and_setup() is a wrapper around mysql_query that caches the connection to the MySQL database (returned by mysql_connect).)

The idea is simple. Use PHP function eval() to introduce variables in caller's scope corresponding to the schema of the result set. (In the above example the variables $name and $email).

It is done via two functions: db_one_row() and db_multi_row(). The first function is for database calls that return a result set which is empty or has one row. The second is for database calls that have a result set of any size. The second approach returns an iterator object.

Using db_one_row():

db_one_row("SELECT email, name FROM email_addresses ORDER BY date DESC LIMIT 1");
echo "The last added email address is $email for user $name";

Here the call to db_one_row introduces and sets the variables $email and $name in caller's scope.

Using db_multi_row():

echo "The last ten added email addresses are:"
$i = db_multi_row("SELECT email, name FROM email_addresses ORDER BY date DESC LIMIT 10");
while ($i.next()) echo "$email for user $name";

Here each call to $i.next() introduces and sets the variables $email and $name in caller's scope.

The source code and demo as a zip file. Just the ez-db-access.php file.