Db_Helper

The database helper class is used for interacting with the database absent of an ActiveRecord model. It allows you to send a direct query to the database.

Db_Helper::scalar($sql)

Fetches and returns a single value from the database. Example:

$user_count = Db_DbHelper::scalar('select count(*) from blog_posts');

Db_Helper::query($sql)

Performs a database query with no expected return result. Example:

Db_DbHelper::query('update blog_posts set title="New title" where id = 1');

Db_Helper::query_array($sql)

Returns a list of database records with each record represented as an array. Example:

$posts = Db_DbHelper::query_array('select * from blog_posts');

This query will return an array, each item in the array is another array with an index key that matches the blog_posts table fields.

Db_Helper::object_array($sql)

Returns a list of database records with each record represented as an object. Example:

$posts = Db_DbHelper::object_array('select * from blog_posts');

This query also returns an array, however each item in the array is an object with properties that match the blog_posts table fields. The object is a stdClass and has no methods.

Db_Helper::object($sql)

Returns a single object with properties that match the resulting query's table fields.

$post = Db_DbHelper::object('select * from blog_posts where id = 1');

This query will return an object with properties that match the blog_posts table fields. The object is a stdClass and has no methods.

Passing Parameters to Queries

It is common that you will need to pass parameters to your SQL queries. All methods presented above support a second parameter which can be used for setting values in the query string. To specify a parameter use a colon character before the parameter name. For example:

$user_email = Db_DbHelper::scalar('select email from users where id=:user_id', array('user_id' => 2));


// -- OR --

Db_DbHelper::query('update blog_posts set title=:new_title where id=:post_id', array(
	'new_title' => $title, 
	'post_id' => 1
));