DataMapper OverZealous Edition


Utility Methods

Query

This method functions in the same way as CodeIgniter's Query method except that the object is populated with the returned results.

Use this method at your own risk as it will only be as reliable as your query. I highly recommend using the binding approach so your data is automatically escaped.

The Query method will populate the object with the results so it is very important to remember that you should be querying for data from the objects table. For example:

// Create user object
$u = new User();

// SQL query on users table
$sql = "SELECT * FROM `users` WHERE `username` = 'Fred Smith' AND `status` = 'active'";

// Run query to populate user object with the results
$u->query($sql);

Obviously you wouldn't use the Query method for the above situation since DataMapper's Get method would be more appropriate.

As I mentioned before, it is recommended you use bindings when using the Query method. For example, doing the same as above but with bindings:

// Create user object
$u = new User();

// SQL query on users table
$sql = "SELECT * FROM `users` WHERE `username` = ? AND `status` = ?";

// Binding values
$binds = array('Fred Smith', 'active');

// Run query to populate user object with the results
$u->query($sql, $binds);

The question marks in the query are automatically replaced with the values in the array in the second parameter of the Query method.

 

Add Table Name

This method will add the object's table name to the provided field.

Useful for the query method, as well as when you need to run more complicated queries using the normal methods from get and get advanced.

Arguments

$u = new User();
$u->where( 'UPPER(' . $u->add_table_name('name') . ') <>', 'SECRET')->get();

// Produces
SELECT * FROM `users`
WHERE UPPER(`users`.`name`) <> 'SECRET'

The benefit of this method is you are no longer hard-coding the table name. It may or may not be worth it for your application.

 

Check Last Query

This method allows you to debug the last query that was processed. In its simplest form, it outputs the last query, formatted and placed inside <pre> tags.

You can also pass as the first argument in a two-item array with alternative delimiters, or FALSE for no delimiters. The second argument, when TRUE, prevents the method from automatically outputting the query to the browser.

Example

$u = new User();
$u->where('name', 'Joe')->get();
$u->check_last_query();
Outputs to the browser:
SELECT `users`.*
FROM `users`
WHERE `users`.`name` = 'Joe'