Query Builder Class¶
Codingox gives you access to a Query Builder class. This pattern allows information to be retrieved, inserted, and updated in your database with minimal scripting. In some cases only one or two lines of code are necessary to perform a database action. Codingox does not require that each database table be its own class file. It instead provides a more simplified interface.
Selecting Data¶
The following functions allow you to build SQL SELECT statements.
$this->db->get()
Runs the selection query and returns the result. Can be used by itself to retrieve all records from a table:
$query = $this->db->get('mytable'); // Produces: SELECT * FROM mytable
You’ll notice that the above function is assigned to a variable named $query, which can be used to show the results:
$query = $this->db->get('mytable');
foreach ($query->findAll() as $row)
{
echo $row['title'];
}
Please visit the result functions page for a full discussion regarding result generation.
$this->db->get_where()
Identical to the above function except that it permits you to add a “where” clause in the second parameter, instead of using the db->where() function:
$query = $this->db->get_where('mytable', array('id' => $id));
Please read the about the where function below for more information.
$this->db->select()
Permits you to write the SELECT portion of your query:
$this->db->select('title, content, date');
$query = $this->db->get('mytable');
// Executes: SELECT title, content, date FROM mytable
Note
If you are selecting all (*) from a table you do not need to use this function. When omitted, Codingox assumes that you wish to select all fields and automatically adds ‘SELECT *’.
$this->db->selectMax()
Writes a SELECT MAX(field)
portion for your query. You can optionally
include a second parameter to rename the resulting field.
$this->db->selectMax('age');
$query = $this->db->get('members'); // Produces: SELECT MAX(age) as age FROM members
$this->db->selectMax('age', 'member_age');
$query = $this->db->get('members'); // Produces: SELECT MAX(age) as member_age FROM members
$this->db->selectMin()
Writes a “SELECT MIN(field)” portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.
$this->db->selectMin('age');
$query = $this->db->get('members'); // Produces: SELECT MIN(age) as age FROM members
$this->db->selectAvg()
Writes a “SELECT AVG(field)” portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.
$this->db->selectAvg('age');
$query = $this->db->get('members'); // Produces: SELECT AVG(age) as age FROM members
$this->db->selectSum()
Writes a “SELECT SUM(field)” portion for your query. As with select_max(), You can optionally include a second parameter to rename the resulting field.
$this->db->selectSum('age');
$query = $this->db->get('members'); // Produces: SELECT SUM(age) as age FROM members
$this->db->from()
Permits you to write the FROM portion of your query:
$this->db->select('title, content, date');
$this->db->from('mytable');
$query = $this->db->get(); // Produces: SELECT title, content, date FROM mytable
Note
As shown earlier, the FROM portion of your query can be specified in the $this->db->get() function, so use whichever method you prefer.
$this->db->join()
Permits you to write the JOIN portion of your query:
$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
// Produces:
// SELECT * FROM blogs JOIN comments ON comments.id = blogs.id
Looking for Specific Data¶
$this->db->where()
This function enables you to set WHERE clauses using one of four methods:
Note
All values passed to this function are escaped automatically, producing safer queries.
-
Simple key/value method:
$this->db->where('name', $name); // Produces: WHERE name = 'Joe'
Notice that the equal sign is added for you.
If you use multiple function calls they will be chained together with AND between them:
$this->db->where('name', $name); $this->db->where('title', $title); $this->db->where('status', $status); // WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
-
Custom key/value method:
You can include an operator in the first parameter in order to control the comparison:
$this->db->where('name != $name'); $this->db->andWhere('id < $id'); // Produces: WHERE name != 'Joe' AND id < 45
-
Associative array method:
$array = array('name' => $name, 'title' => $title, 'status' => $status); $this->db->where($array); // Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
-
- Custom string:
-
You can write your own clauses manually:
$where = "name='Joe' AND status='boss' OR status='active'"; $this->db->where($where);
$this->db->orWhere()
This function is identical to the one above, except that multiple instances are joined by OR:
$this->db->where('name != $name');
$this->db->orWhere('id > $id'); // Produces: WHERE name != 'Joe' OR id > 50
Looking for Similar Data¶
$this->db->like()
This method enables you to generate LIKE clauses, useful for doing searches.
Note
All values passed to this method are escaped automatically.
-
Simple key/value method:
$this->db->like('title', 'match'); // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
If you use multiple method calls they will be chained together with AND between them:
$this->db->like('title', 'match'); $this->db->like('body', 'match'); // WHERE `title` LIKE '%match%' ESCAPE '!' AND `body` LIKE '%match% ESCAPE '!'
-
Associative array method:
$array = array('title' => $match, 'page1' => $match, 'page2' => $match); $this->db->like($array); // WHERE `title` LIKE '%match%' ESCAPE '!' AND `page1` LIKE '%match%' ESCAPE '!' AND `page2` LIKE '%match%' ESCAPE '!'
$this->db->orLike()
This method is identical to the one above, except that multiple instances are joined by OR:
$this->db->like('title', 'match'); $this->db->orLike('body', $match);
// WHERE `title` LIKE '%match%' ESCAPE '!' OR `body` LIKE '%match%' ESCAPE '!'
$this->db->notLike()
This method is identical to like()
,
except that it generates
NOT LIKE statements:
$this->db->notLike('title', 'match'); // WHERE `title` NOT LIKE '%match% ESCAPE '!'
$this->db->orNotLike()
This method is identical to notLike()
,
except that multiple
instances are joined by OR:
$this->db->like('title', 'match');
$this->db->orNotLike('body', 'match');
// WHERE `title` LIKE '%match% OR `body` NOT LIKE '%match%' ESCAPE '!'
$this->db->groupBy()
Permits you to write the GROUP BY portion of your query:
$this->db->groupBy("title"); // Produces: GROUP BY title
You can also pass an array of multiple values as well:
$this->db->groupBy(array("title", "date")); // Produces: GROUP BY title, date
Ordering results¶
$this->db->orderBy()
Lets you set an ORDER BY clause.
The first parameter contains the name of the column you would like to order by.
The second parameter lets you set the direction of the result. Options are ASC AND DESC.
$this->db->orderBy('title', 'DESC');
// Produces: ORDER BY `title` DESC
You can also pass your own string in the first parameter:
$this->db->orderBy('title DESC, name ASC');
// Produces: ORDER BY `title` DESC, `name` ASC
Or multiple function calls can be made if you need multiple fields.
$this->db->orderBy('title', 'DESC');
$this->db->orderBy('name', 'ASC');
// Produces: ORDER BY `title` DESC, `name` ASC
Limiting or Counting Results¶
$this->db->limit()
Lets you limit the number of rows you would like returned by the query:
$this->db->limit(10); // Produces: LIMIT 10
The second parameter lets you set a result offset.
$this->db->limit(10, 20); // Produces: LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)
Inserting Data¶
$this->db->insert()
Generates an insert string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:
$data = array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
);
$this->db->insert('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')
$this->db->insertBatch()
Generates an insert string based on the data you supply, and runs the query. You can pass an array to the function. Here is an example using an array:
$data = array(
array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
),
array(
'title' => 'Another title',
'name' => 'Another Name',
'date' => 'Another date'
)
);
$this->db->insertBatch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
The first parameter will contain the table name, the second is an associative array of values.
Note
All values are escaped automatically producing safer queries.
Updating Data¶
$this->db->update()
Generates an update string and runs the query based on the data you supply. You can pass an array to the function. Here is an example using an array:
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id = $id');
$this->db->update('mytable', $data);
// Produces:
//
// UPDATE mytable
// SET title = '{$title}', name = '{$name}', date = '{$date}'
// WHERE id = $id
Note
All values are escaped automatically producing safer queries.
You’ll notice the use of the $this->db->where() function, enabling you to set the WHERE clause. You can optionally pass this information directly into the update function as a string:
$this->db->update('mytable', $data, "id = 4");
Or as an array:
$this->db->update('mytable', $data, array('id' => $id));
You may also use the $this->db->set() function described above when performing updates.
Deleting Data¶
$this->db->delete()
Generates a delete SQL string and runs the query.
$this->db->delete('mytable', array('id' => $id)); // Produces: // DELETE FROM mytable // WHERE id = $id
The first parameter is the table name, the second is the where clause. You can also use the where() or or_where() functions instead of passing the data to the second parameter of the function:
$this->db->where('id = $id');
$this->db->delete('mytable');
// Produces:
// DELETE FROM mytable
// WHERE id = $id
An array of table names can be passed into delete() if you would like to delete data from more than 1 table.
$tables = array('table1', 'table2', 'table3');
$this->db->where('id = "5"');
$this->db->delete($tables);
$this->db->truncate()
Generates a truncate SQL string and runs the query.
$this->db->from('mytable');
$this->db->truncate();
// or
$this->db->truncate('mytable');
// Produce:
// TRUNCATE mytable
Note
If the TRUNCATE command isn’t available, truncate() will execute as “DELETE FROM table”.
Class Reference¶
-
class
QueryBuilder
¶ -
-
set_prefix
([$prefix = ''])¶ -
Parameters: - $prefix (string) – The new prefix to use
Returns: The DB prefix in use
Return type: string
Sets the database prefix, without having to reconnect.
-
prefix
([$table = ''])¶ -
Parameters: - $table (string) – The table name to prefix
Returns: The prefixed table name
Return type: string
Prepends a database prefix, if one exists in configuration.
-
get
($table)¶ -
Parameters: - $table (string) – The table to query
Return type: Query Result
Compiles and runs SELECT statement based on the already called Query Builder methods.
-
get_where
($table, $where = NULL)¶ -
Parameters: - $table (mixed) – The table(s) to fetch data from; string or array
- $where (string) – The WHERE clause
Return type: Query Result
Same as
get()
, but also allows the WHERE to be added directly.
-
select
($select = '*')¶ -
Parameters: - $select (string) – The SELECT portion of a query
Return type: Query Result
Adds a SELECT clause to a query.
-
selectAvg
($select = '')¶ -
Parameters: - $select (string) – Field to compute the average of
Return type: Query Result
Adds a SELECT AVG(field) clause to a query.
-
selectMax
($select = '')¶ -
Parameters: - $select (string) – Field to compute the maximum of
Return type: Query Result
Adds a SELECT MAX(field) clause to a query.
-
selectMin
($select = '')¶ -
Parameters: - $select (string) – Field to compute the minimum of
Return type: Query Result
Adds a SELECT MIN(field) clause to a query.
-
selectSum
($select = '')¶ -
Parameters: - $select (string) – Field to compute the sum of
Return type: Query Result
Adds a SELECT SUM(field) clause to a query.
-
from
($from)¶ -
Parameters: - $from (mixed) – Table name(s); string or array
Return type: Query Builder
Specifies the FROM clause of a query.
-
join
($table, $cond)¶ -
Parameters: - $table (string) – Table name to join
- $cond (string) – The JOIN ON condition
Return type: Query Builder
Adds a JOIN clause to a query.
-
where
($key, $value = NULL)¶ -
Parameters: - $key (mixed) – Name of field to compare, or associative array
- $value (mixed) – If a single key, compared to this value
Returns: DB_Query_Builder instance
Return type: String
Generates the WHERE portion of the query. Separates multiple calls with ‘AND’.
-
orWhere
($key, $value = NULL)¶ -
Parameters: - $key (mixed) – Name of field to compare, or associative array
- $value (mixed) – If a single key, compared to this value
Returns: DB_Query_Builder instance
Return type: String
Generates the WHERE portion of the query. Separates multiple calls with ‘OR’.
-
like
($field, $match = '')¶ -
Parameters: - $field (string) – Field name
- $match (string) – Text portion to match
Returns: Query_Builder instance
Return type: Query_Builder
Adds a LIKE clause to a query, separating multiple calls with AND.
-
orLike
($field, $match = '')¶ -
Parameters: - $field (string) – Field name
- $match (string) – Text portion to match
Returns: Query_Builder instance
Return type: Query_Builder
Adds a LIKE clause to a query, separating multiple class with OR.
-
notLike
($field, $match = '')¶ -
Parameters: - $field (string) – Field name
- $match (string) – Text portion to match
Returns: Query_Builder instance
Return type: Query_Builder
Adds a NOT LIKE clause to a query, separating multiple calls with AND.
-
orNotLike
($field, $match = '')¶ -
Parameters: - $field (string) – Field name
- $match (string) – Text portion to match
Returns: Query_Builder instance
Return type: Query_Builder
Adds a NOT LIKE clause to a query, separating multiple calls with OR.
-
groupBy
($by)¶ -
Parameters: - $by (mixed) – Field(s) to group by; string or array
Returns: Query_Builder instance
Return type: Query_Builder
Adds a GROUP BY clause to a query.
-
orderBy
($orderby, $direction = '')¶ -
Parameters: - $orderby (string) – Field to order by
- $direction (string) – The order requested - ASC or DESC
Returns: Query_Builder instance
Return type: Query_Builder
Adds an ORDER BY clause to a query.
-
limit
($value, $offset = 0)¶ -
Parameters: - $value (int) – Number of rows to limit the results to
- $offset (int) – Number of rows to skip
Returns: Query_Builder instance
Return type: Query_Builder
Adds LIMIT and OFFSET clauses to a query.
-
offset
($offset)¶ -
Parameters: - $offset (int) – Number of rows to skip
Returns: Query_Builder instance
Return type: Query_Builder
Adds an OFFSET clause to a query.
-
insert
($table = '', $set = NULL)¶ -
Parameters: - $table (string) – Table name
- $set (array) – An associative array of field/value pairs
Returns: TRUE on success, FALSE on failure
Return type: bool
Compiles and executes an INSERT statement.
-
insertBatch
($table, $set = NULL)¶ -
Parameters: - $table (string) – Table name
- $set (array) – Data to insert
Returns: Number of rows inserted or FALSE on failure
Return type: mixed
Compiles and executes batch
INSERT
statements.
-
update
($table, $set = NULL, $where = NULL)¶ -
Parameters: - $table (string) – Table name
- $set (array) – An associative array of field/value pairs
- $where (string) – The WHERE clause
Returns: TRUE on success, FALSE on failure
Return type: bool
Compiles and executes an UPDATE statement.
-
delete
($table = '', $where = '')¶ -
Parameters: - $table (mixed) – The table(s) to delete from; string or array
- $where (string) – The WHERE clause
Returns: Query_builder instance or FALSE on failure
Return type: bool
Compiles and executes a DELETE query.
-
truncate
($table)¶ -
Parameters: - $table (string) – Table name
Returns: TRUE on success, FALSE on failure
Return type: bool
Executes a TRUNCATE statement on a table.
Note
If the database platform in use doesn’t support TRUNCATE, a DELETE statement will be used instead.
-