| Status | Draft |
|---|---|
| Todo | escaping data, prepared statements when they're finished |
$db→query($sql) carries out the sql given. Will also connect to the database if it wasn't connected before. Returns a result object. Does not escape table names or anything.
$query = $db->query('SELECT username FROM users');
$db→last_query($sql) returns a string containing the last run query.
$last_query = $db->last_query();
$db→escape( $value ) returns a string which is the escaped version of the $value. This escaped string is suitable (and safe) to be used in an SQL statement.
In the following example we'll show how to query a database and retrieve all usernames from the users table.
class User_Controller extends Controller { public function listusers(){ $db=new Database; $result= $db->query('SELECT username FROM users'); echo '<h2>'.$db->last_query().'</h2>'; echo '<ul>'; foreach($result as $row) { echo '<li>'.$row->username.'</li>'; } echo '</ul>'; } }
Now if you enter www.yoursite.com/user/listusers you'll see a list of users with a heading of the query above it.
<h2>SELECT username FROM users</h2> <ul> <li>John</li> <li>Michael</li> </ul>
The database library has support for query binding. It allows you to create custom built queries and have the library escape your input values for you.
$query = $db->query('SELECT `username` FROM `users` where `id` = ?', array(12)); // OR $query = $db->query('SELECT `username` FROM `users` where `id` = ? and `foo` = ?', 12, 'bar');
In addition you can use the Query Builder portion of the database library to create database agnostic access.
After you perform your query, you get a Query Result object back.
In case you need to do a where or join (or other) clause to be taken literally, you can use a database expression. For example:
$query = $db->set('number', new Database_Expression('number+1'));