You are currently browsing Crystal’s documentation for the 0.4 version - Switch to version: 0.3
Query builders
With Crystal you can write queries in the typical for the PHP database libraries manner
$where = array('id' => '2','column1' => '5','column2' => 'value')
$result = $db->select('column1','column2')->from('table')->where($where)->fetch_all();
For readability you can write queries with something I call SQL partials. For example:
$result = $db->select('column1','column2')->from('table')->where('id','2')->and('column1','5')->and('column2','value')->fetch_all();
//produces SELECT `column1`, `column2` FROM `table` WHERE `id`='2' AND `column1` ='5' AND `column2` = 'value'
As you can see it is the same amount of code, but with 3 major advantages:
- You are not limited by Crystal - if you know SQL, you can write your queries without additional documentation for the database wrapper.
- You queries are database independent - the same query works with MySql, Postgresql, Sqlite or any database Crystal supports in the future.
- Your data is properly escaped.
Method chain
All functions in Crystal belong to one global super object. Because of this fact, you can write much more concise queries
// Instead of this one
$db->select('column1, column2);
$db->from('table');
$db->fetch_all();
// You can write this
$db->select('column1, column2)->from('table')->fetch_all();