Query Builder Class

CodeIgniter gives you access to a Query Builder class. This patternallows information to be retrieved, inserted, and updated in yourdatabase with minimal scripting. In some cases, only one or two linesof code are necessary to perform a database action.CodeIgniter does not require that each database table be its own classfile. It instead provides a more simplified interface.

Beyond simplicity, a major benefit to using the Query Builder featuresis that it allows you to create database independent applications, sincethe query syntax is generated by each database adapter. It also allowsfor safer queries, since the values are escaped automatically by thesystem.

Loading the Query Builder

The Query Builder is loaded through the table() method on thedatabase connection. This sets the FROM portion of the query for youand returns a new instance of the Query Builder class:

  1. $db = \Config\Database::connect();
  2. $builder = $db->table('users');

The Query Builder is only loaded into memory when you specifically requestthe class, so no resources are used by default.

Selecting Data

The following functions allow you to build SQL SELECT statements.

$builder->get()

Runs the selection query and returns the result. Can be used by itselfto retrieve all records from a table:

  1. $builder = $db->table('mytable');
  2. $query = $builder->get(); // Produces: SELECT * FROM mytable

The first and second parameters enable you to set a limit and offsetclause:

  1. $query = $builder->get(10, 20);
  2.  
  3. // Executes: SELECT * FROM mytable LIMIT 20, 10
  4. // (in MySQL. Other databases have slightly different syntax)

You’ll notice that the above function is assigned to a variable named$query, which can be used to show the results:

  1. $query = $builder->get();
  2.  
  3. foreach ($query->getResult() as $row)
  4. {
  5. echo $row->title;
  6. }

Please visit the result functions page for a fulldiscussion regarding result generation.

$builder->getCompiledSelect()

Compiles the selection query just like $builder->get() but does not _run_the query. This method simply returns the SQL query as a string.

Example:

  1. $sql = $builder->getCompiledSelect();
  2. echo $sql;
  3.  
  4. // Prints string: SELECT * FROM mytable

The first parameter enables you to set whether or not the query builder querywill be reset (by default it will be reset, just like when using $builder->get()):

  1. echo $builder->limit(10,20)->getCompiledSelect(false);
  2.  
  3. // Prints string: SELECT * FROM mytable LIMIT 20, 10
  4. // (in MySQL. Other databases have slightly different syntax)
  5.  
  6. echo $builder->select('title, content, date')->getCompiledSelect();
  7.  
  8. // Prints string: SELECT title, content, date FROM mytable LIMIT 20, 10

The key thing to notice in the above example is that the second query did notutilize $builder->from() and did not pass a table name into the firstparameter. The reason for this outcome is because the query has not beenexecuted using $builder->get() which resets values or reset directlyusing $builder->resetQuery().

$builder->getWhere()

Identical to the get() function except that it permits you to add a“where” clause in the first parameter, instead of using the db->where()function:

  1. $query = $builder->getWhere(['id' => $id], $limit, $offset);

Please read about the where function below for more information.

$builder->select()

Permits you to write the SELECT portion of your query:

  1. $builder->select('title, content, date');
  2. $query = $builder->get();
  3.  
  4. // Executes: SELECT title, content, date FROM mytable

Note

If you are selecting all () from a table you do not need touse this function. When omitted, CodeIgniter assumes that you wishto select all fields and automatically adds ‘SELECT ’.

$builder->select() accepts an optional second parameter. If you set itto FALSE, CodeIgniter will not try to protect your field or table names.This is useful if you need a compound select statement where automaticescaping of fields may break them.

  1. $builder->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4) AS amount_paid', FALSE);
  2. $query = $builder->get();

$builder->selectMax()

Writes a SELECT MAX(field) portion for your query. You can optionallyinclude a second parameter to rename the resulting field.

  1. $builder->selectMax('age');
  2. $query = $builder->get(); // Produces: SELECT MAX(age) as age FROM mytable
  3.  
  4. $builder->selectMax('age', 'member_age');
  5. $query = $builder->get(); // Produces: SELECT MAX(age) as member_age FROM mytable

$builder->selectMin()

Writes a “SELECT MIN(field)” portion for your query. As withselectMax(), You can optionally include a second parameter to renamethe resulting field.

  1. $builder->selectMin('age');
  2. $query = $builder->get(); // Produces: SELECT MIN(age) as age FROM mytable

$builder->selectAvg()

Writes a “SELECT AVG(field)” portion for your query. As withselectMax(), You can optionally include a second parameter to renamethe resulting field.

  1. $builder->selectAvg('age');
  2. $query = $builder->get(); // Produces: SELECT AVG(age) as age FROM mytable

$builder->selectSum()

Writes a “SELECT SUM(field)” portion for your query. As withselectMax(), You can optionally include a second parameter to renamethe resulting field.

  1. $builder->selectSum('age');
  2. $query = $builder->get(); // Produces: SELECT SUM(age) as age FROM mytable

$builder->selectCount()

Writes a “SELECT COUNT(field)” portion for your query. As withselectMax(), You can optionally include a second parameter to renamethe resulting field.

Note

This method is particularly helpful when used with groupBy(). Forcounting results generally see countAll() or countAllResults().

  1. $builder->selectCount('age');
  2. $query = $builder->get(); // Produces: SELECT COUNT(age) as age FROM mytable

$builder->from()

Permits you to write the FROM portion of your query:

  1. $builder->select('title, content, date');
  2. $builder->from('mytable');
  3. $query = $builder->get(); // Produces: SELECT title, content, date FROM mytable

Note

As shown earlier, the FROM portion of your query can is specifiedin the $db->table() function. Additional calls to from() will add more tablesto the FROM portion of your query.

$builder->join()

Permits you to write the JOIN portion of your query:

  1. $builder->db->table('blog');
  2. $builder->select('*');
  3. $builder->join('comments', 'comments.id = blogs.id');
  4. $query = $builder->get();
  5.  
  6. // Produces:
  7. // SELECT * FROM blogs JOIN comments ON comments.id = blogs.id

Multiple function calls can be made if you need several joins in onequery.

If you need a specific type of JOIN you can specify it via the thirdparameter of the function. Options are: left, right, outer, inner, leftouter, and right outer.

  1. $builder->join('comments', 'comments.id = blogs.id', 'left');
  2. // Produces: LEFT JOIN comments ON comments.id = blogs.id

Looking for Specific Data

$builder->where()

This function enables you to set WHERE clauses using one of fourmethods:

Note

All values passed to this function are escaped automatically,producing safer queries.

  • Simple key/value method:
  1. $builder->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 withAND between them:

  1. $builder->where('name', $name);$builder->where('title', $title);$builder->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 tocontrol the comparison:

  1. $builder->where('name !=', $name);$builder->where('id <', $id); // Produces: WHERE name != 'Joe' AND id < 45
  • Associative array method:
  1. $array = ['name' => $name, 'title' => $title, 'status' => $status];$builder->where($array);// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'

You can include your own operators using this method as well:

  1. $array = ['name !=' => $name, 'id <' => $id, 'date >' => $date];$builder->where($array);
    • Custom string:

You can write your own clauses manually:

  1. $where = "name='Joe' AND status='boss' OR status='active'";$builder->where($where);

$builder->where() accepts an optional third parameter. If you set it toFALSE, CodeIgniter will not try to protect your field or table names.

  1. $builder->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
    • Subqueries:
    • You can use an anonymous function to create a subquery.
  1. $builder->where('advance_amount <', function(BaseBuilder $builder) {
  2. return $builder->select('MAX(advance_amount)', false)->from('orders')->where('id >', 2);
  3. });
  4. // Produces: WHERE "advance_amount" < (SELECT MAX(advance_amount) FROM "orders" WHERE "id" > 2)

$builder->orWhere()

This function is identical to the one above, except that multipleinstances are joined by OR

  1. $builder->where('name !=', $name);$builder->orWhere('id >', $id); // Produces: WHERE name != 'Joe' OR id > 50

$builder->whereIn()

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with AND ifappropriate

  1. $names = ['Frank', 'Todd', 'James'];$builder->whereIn('username', $names);// Produces: WHERE username IN ('Frank', 'Todd', 'James')

You can use subqueries instead of an array of values.

  1. $builder->whereIn('id', function(BaseBuilder $builder) { return $builder->select('job_id')->from('users_jobs')->where('user_id', 3);});// Produces: WHERE "id" IN (SELECT "job_id" FROM "users_jobs" WHERE "user_id" = 3)

$builder->orWhereIn()

Generates a WHERE field IN (‘item’, ‘item’) SQL query joined with OR ifappropriate

  1. $names = ['Frank', 'Todd', 'James'];$builder->orWhereIn('username', $names);// Produces: OR username IN ('Frank', 'Todd', 'James')

You can use subqueries instead of an array of values.

  1. $builder->orWhereIn('id', function(BaseBuilder $builder) { return $builder->select('job_id')->from('users_jobs')->where('user_id', 3);});// Produces: OR "id" IN (SELECT "job_id" FROM "users_jobs" WHERE "user_id" = 3)

$builder->whereNotIn()

Generates a WHERE field NOT IN (‘item’, ‘item’) SQL query joined withAND if appropriate

  1. $names = ['Frank', 'Todd', 'James'];$builder->whereNotIn('username', $names);// Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')

You can use subqueries instead of an array of values.

  1. $builder->whereNotIn('id', function(BaseBuilder $builder) { return $builder->select('job_id')->from('users_jobs')->where('user_id', 3);});// Produces: WHERE "id" NOT IN (SELECT "job_id" FROM "users_jobs" WHERE "user_id" = 3)

$builder->orWhereNotIn()

Generates a WHERE field NOT IN (‘item’, ‘item’) SQL query joined with ORif appropriate

  1. $names = ['Frank', 'Todd', 'James'];$builder->orWhereNotIn('username', $names);// Produces: OR username NOT IN ('Frank', 'Todd', 'James')

You can use subqueries instead of an array of values.

  1. $builder->orWhereNotIn('id', function(BaseBuilder $builder) { return $builder->select('job_id')->from('users_jobs')->where('user_id', 3);});// Produces: OR "id" NOT IN (SELECT "job_id" FROM "users_jobs" WHERE "user_id" = 3)

Looking for Similar Data

$builder->like()

This method enables you to generate LIKE clauses, useful for doingsearches.

Note

All values passed to this method are escaped automatically.

Note

All like* method variations can be forced to perform case-insensitive searches by passinga fifth parameter of true to the method. This will use platform-specific features where availableotherwise, will force the values to be lowercase, i.e. WHERE LOWER(column) LIKE '%search%'. Thismay require indexes to be made for LOWER(column) instead of column to be effective.

  • Simple key/value method:
  1. $builder->like('title', 'match');// Produces: WHERE title LIKE '%match%' ESCAPE '!'

If you use multiple method calls they will be chained together withAND between them:

  1. $builder->like('title', 'match');$builder->like('body', 'match');// WHERE title LIKE '%match%' ESCAPE '!' AND body LIKE '%match% ESCAPE '!'

If you want to control where the wildcard (%) is placed, you can usean optional third argument. Your options are ‘before’, ‘after’ and‘both’ (which is the default).

  1. $builder->like('title', 'match', 'before'); // Produces: WHERE title LIKE '%match' ESCAPE '!'$builder->like('title', 'match', 'after'); // Produces: WHERE title LIKE 'match%' ESCAPE '!'$builder->like('title', 'match', 'both'); // Produces: WHERE title LIKE '%match%' ESCAPE '!'
  • Associative array method:
  1. $array = ['title' => $match, 'page1' => $match, 'page2' => $match];$builder->like($array);// WHERE title LIKE '%match%' ESCAPE '!' AND page1 LIKE '%match%' ESCAPE '!' AND page2 LIKE '%match%' ESCAPE '!'

$builder->orLike()

This method is identical to the one above, except that multipleinstances are joined by OR:

  1. $builder->like('title', 'match'); $builder->orLike('body', $match);
  2. // WHERE `title` LIKE '%match%' ESCAPE '!' OR `body` LIKE '%match%' ESCAPE '!'

$builder->notLike()

This method is identical to like(), except that it generatesNOT LIKE statements:

  1. $builder->notLike('title', 'match'); // WHERE `title` NOT LIKE '%match% ESCAPE '!'

$builder->orNotLike()

This method is identical to notLike(), except that multipleinstances are joined by OR:

  1. $builder->like('title', 'match');
  2. $builder->orNotLike('body', 'match');
  3. // WHERE `title` LIKE '%match% OR `body` NOT LIKE '%match%' ESCAPE '!'

$builder->groupBy()

Permits you to write the GROUP BY portion of your query:

  1. $builder->groupBy("title"); // Produces: GROUP BY title

You can also pass an array of multiple values as well:

  1. $builder->groupBy(["title", "date"]); // Produces: GROUP BY title, date

$builder->distinct()

Adds the “DISTINCT” keyword to a query

  1. $builder->distinct();
  2. $builder->get(); // Produces: SELECT DISTINCT * FROM mytable

$builder->having()

Permits you to write the HAVING portion of your query. There are 2possible syntaxes, 1 argument or 2:

  1. $builder->having('user_id = 45'); // Produces: HAVING user_id = 45
  2. $builder->having('user_id', 45); // Produces: HAVING user_id = 45

You can also pass an array of multiple values as well:

  1. $builder->having(['title =' => 'My Title', 'id <' => $id]);
  2. // Produces: HAVING title = 'My Title', id < 45

If you are using a database that CodeIgniter escapes queries for, youcan prevent escaping content by passing an optional third argument, andsetting it to FALSE.

  1. $builder->having('user_id', 45); // Produces: HAVING `user_id` = 45 in some databases such as MySQL
  2. $builder->having('user_id', 45, FALSE); // Produces: HAVING user_id = 45

$builder->orHaving()

Identical to having(), only separates multiple clauses with “OR”.

$builder->havingIn()

Generates a HAVING field IN (‘item’, ‘item’) SQL query joined with AND ifappropriate

  1. $groups = [1, 2, 3];$builder->havingIn('group_id', $groups);// Produces: HAVING group_id IN (1, 2, 3)

You can use subqueries instead of an array of values.

  1. $builder->havingIn('id', function(BaseBuilder $builder) { return $builder->select('user_id')->from('users_jobs')->where('group_id', 3);});// Produces: HAVING "id" IN (SELECT "user_id" FROM "users_jobs" WHERE "group_id" = 3)

$builder->orHavingIn()

Generates a HAVING field IN (‘item’, ‘item’) SQL query joined with OR ifappropriate

  1. $groups = [1, 2, 3];$builder->orHavingIn('group_id', $groups);// Produces: OR group_id IN (1, 2, 3)

You can use subqueries instead of an array of values.

  1. $builder->orHavingIn('id', function(BaseBuilder $builder) { return $builder->select('user_id')->from('users_jobs')->where('group_id', 3);});// Produces: OR "id" IN (SELECT "user_id" FROM "users_jobs" WHERE "group_id" = 3)

$builder->havingNotIn()

Generates a HAVING field NOT IN (‘item’, ‘item’) SQL query joined withAND if appropriate

  1. $groups = [1, 2, 3];$builder->havingNotIn('group_id', $groups);// Produces: HAVING group_id NOT IN (1, 2, 3)

You can use subqueries instead of an array of values.

  1. $builder->havingNotIn('id', function(BaseBuilder $builder) { return $builder->select('user_id')->from('users_jobs')->where('group_id', 3);});// Produces: HAVING "id" NOT IN (SELECT "user_id" FROM "users_jobs" WHERE "group_id" = 3)

$builder->orHavingNotIn()

Generates a HAVING field NOT IN (‘item’, ‘item’) SQL query joined with ORif appropriate

  1. $groups = [1, 2, 3];$builder->havingNotIn('group_id', $groups);// Produces: OR group_id NOT IN (1, 2, 3)

You can use subqueries instead of an array of values.

  1. $builder->orHavingNotIn('id', function(BaseBuilder $builder) { return $builder->select('user_id')->from('users_jobs')->where('group_id', 3);});// Produces: OR "id" NOT IN (SELECT "user_id" FROM "users_jobs" WHERE "group_id" = 3)

$builder->havingLike()

This method enables you to generate LIKE clauses for HAVING part or the query, useful for doingsearches.

Note

All values passed to this method are escaped automatically.

Note

All havingLike* method variations can be forced to perform case-insensitive searches by passinga fifth parameter of true to the method. This will use platform-specific features where availableotherwise, will force the values to be lowercase, i.e. HAVING LOWER(column) LIKE '%search%'. Thismay require indexes to be made for LOWER(column) instead of column to be effective.

  • Simple key/value method:
  1. $builder->havingLike('title', 'match');// Produces: HAVING title LIKE '%match%' ESCAPE '!'

If you use multiple method calls they will be chained together withAND between them:

  1. $builder->havingLike('title', 'match');$builder->havingLike('body', 'match');// HAVING title LIKE '%match%' ESCAPE '!' AND body LIKE '%match% ESCAPE '!'

If you want to control where the wildcard (%) is placed, you can usean optional third argument. Your options are ‘before’, ‘after’ and‘both’ (which is the default).

  1. $builder->havingLike('title', 'match', 'before'); // Produces: HAVING title LIKE '%match' ESCAPE '!'$builder->havingLike('title', 'match', 'after'); // Produces: HAVING title LIKE 'match%' ESCAPE '!'$builder->havingLike('title', 'match', 'both'); // Produces: HAVING title LIKE '%match%' ESCAPE '!'
  • Associative array method:
  1. $array = ['title' => $match, 'page1' => $match, 'page2' => $match];$builder->havingLike($array);// HAVING title LIKE '%match%' ESCAPE '!' AND page1 LIKE '%match%' ESCAPE '!' AND page2 LIKE '%match%' ESCAPE '!'

$builder->orHavingLike()

This method is identical to the one above, except that multipleinstances are joined by OR:

  1. $builder->havingLike('title', 'match'); $builder->orHavingLike('body', $match);
  2. // HAVING `title` LIKE '%match%' ESCAPE '!' OR `body` LIKE '%match%' ESCAPE '!'

$builder->notHavingLike()

This method is identical to havingLike(), except that it generatesNOT LIKE statements:

  1. $builder->notHavingLike('title', 'match'); // HAVING `title` NOT LIKE '%match% ESCAPE '!'

$builder->orNotHavingLike()

This method is identical to notHavingLike(), except that multipleinstances are joined by OR:

  1. $builder->havingLike('title', 'match');
  2. $builder->orNotHavingLike('body', 'match');
  3. // HAVING `title` LIKE '%match% OR `body` NOT LIKE '%match%' ESCAPE '!'

Ordering results

$builder->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, DESC AND RANDOM.

  1. $builder->orderBy('title', 'DESC');
  2. // Produces: ORDER BY `title` DESC

You can also pass your own string in the first parameter:

  1. $builder->orderBy('title DESC, name ASC');
  2. // Produces: ORDER BY `title` DESC, `name` ASC

Or multiple function calls can be made if you need multiple fields.

  1. $builder->orderBy('title', 'DESC');
  2. $builder->orderBy('name', 'ASC');
  3. // Produces: ORDER BY `title` DESC, `name` ASC

If you choose the RANDOM direction option, then the first parameters willbe ignored, unless you specify a numeric seed value.

  1. $builder->orderBy('title', 'RANDOM');
  2. // Produces: ORDER BY RAND()
  3.  
  4. $builder->orderBy(42, 'RANDOM');
  5. // Produces: ORDER BY RAND(42)

Note

Random ordering is not currently supported in Oracle andwill default to ASC instead.

Limiting or Counting Results

$builder->limit()

Lets you limit the number of rows you would like returned by the query:

  1. $builder->limit(10); // Produces: LIMIT 10

The second parameter lets you set a result offset.

  1. $builder->limit(10, 20); // Produces: LIMIT 20, 10 (in MySQL. Other databases have slightly different syntax)

$builder->countAllResults()

Permits you to determine the number of rows in a particular QueryBuilder query. Queries will accept Query Builder restrictors such aswhere(), orWhere(), like(), orLike(), etc. Example:

  1. echo $builder->countAllResults(); // Produces an integer, like 25
  2. $builder->like('title', 'match');
  3. $builder->from('my_table');
  4. echo $builder->countAllResults(); // Produces an integer, like 17

However, this method also resets any field values that you may have passedto select(). If you need to keep them, you can pass FALSE as thefirst parameter.

echo $builder->countAllResults(false); // Produces an integer, like 17

$builder->countAll()

Permits you to determine the number of rows in a particular table.Example:

  1. echo $builder->countAll(); // Produces an integer, like 25

As is in countAllResult method, this method resets any field values that you may have passedto select() as well. If you need to keep them, you can pass FALSE as thefirst parameter.

Query grouping

Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allowyou to create queries with complex WHERE clauses. Nested groups are supported. Example:

  1. $builder->select('*')->from('my_table')
  2. ->groupStart()
  3. ->where('a', 'a')
  4. ->orGroupStart()
  5. ->where('b', 'b')
  6. ->where('c', 'c')
  7. ->groupEnd()
  8. ->groupEnd()
  9. ->where('d', 'd')
  10. ->get();
  11.  
  12. // Generates:
  13. // SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'

Note

groups need to be balanced, make sure every groupStart() is matched by a groupEnd().

$builder->groupStart()

Starts a new group by adding an opening parenthesis to the WHERE clause of the query.

$builder->orGroupStart()

Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with ‘OR’.

$builder->notGroupStart()

Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with ‘NOT’.

$builder->orNotGroupStart()

Starts a new group by adding an opening parenthesis to the WHERE clause of the query, prefixing it with ‘OR NOT’.

$builder->groupEnd()

Ends the current group by adding a closing parenthesis to the WHERE clause of the query.

$builder->groupHavingStart()

Starts a new group by adding an opening parenthesis to the HAVING clause of the query.

$builder->orGroupHavingStart()

Starts a new group by adding an opening parenthesis to the HAVING clause of the query, prefixing it with ‘OR’.

$builder->notGroupHavingStart()

Starts a new group by adding an opening parenthesis to the HAVING clause of the query, prefixing it with ‘NOT’.

$builder->orNotGroupHavingStart()

Starts a new group by adding an opening parenthesis to the HAVING clause of the query, prefixing it with ‘OR NOT’.

$builder->groupHavingEnd()

Ends the current group by adding a closing parenthesis to the HAVING clause of the query.

Inserting Data

$builder->insert()

Generates an insert string based on the data you supply, and runs thequery. You can either pass an array or an object to thefunction. Here is an example using an array:

  1. $data = [
  2. 'title' => 'My title',
  3. 'name' => 'My Name',
  4. 'date' => 'My date'
  5. ];
  6.  
  7. $builder->insert($data);
  8. // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

The first parameter is an associative array of values.

Here is an example using an object:

  1. /*
  2. class Myclass {
  3. public $title = 'My Title';
  4. public $content = 'My Content';
  5. public $date = 'My Date';
  6. }
  7. */
  8.  
  9. $object = new Myclass;
  10. $builder->insert($object);
  11. // Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')

The first parameter is an object.

Note

All values are escaped automatically producing safer queries.

$builder->ignore()

Generates an insert ignore string based on the data you supply, and runs thequery. So if an entry with the same primary key already exists, the query won’t be inserted.You can optionally pass an boolean to the function. Here is an example using the array of the above example:

  1. $data = [
  2. 'title' => 'My title',
  3. 'name' => 'My Name',
  4. 'date' => 'My date'
  5. ];
  6.  
  7. $builder->ignore(true)->insert($data);
  8. // Produces: INSERT OR IGNORE INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

$builder->getCompiledInsert()

Compiles the insertion query just like $builder->insert() but does notrun the query. This method simply returns the SQL query as a string.

Example:

  1. $data = [
  2. 'title' => 'My title',
  3. 'name' => 'My Name',
  4. 'date' => 'My date'
  5. ];
  6.  
  7. $sql = $builder->set($data)->getCompiledInsert('mytable');
  8. echo $sql;
  9.  
  10. // Produces string: INSERT INTO mytable (`title`, `name`, `date`) VALUES ('My title', 'My name', 'My date')

The second parameter enables you to set whether or not the query builder querywill be reset (by default it will be–just like $builder->insert()):

  1. echo $builder->set('title', 'My Title')->getCompiledInsert('mytable', FALSE);
  2.  
  3. // Produces string: INSERT INTO mytable (`title`) VALUES ('My Title')
  4.  
  5. echo $builder->set('content', 'My Content')->getCompiledInsert();
  6.  
  7. // Produces string: INSERT INTO mytable (`title`, `content`) VALUES ('My Title', 'My Content')

The key thing to notice in the above example is that the second query did notutilize $builder->from() nor did it pass a table name into the firstparameter. The reason this worked is that the query has not been executedusing $builder->insert() which resets values or reset directly using$builder->resetQuery().

Note

This method doesn’t work for batched inserts.

$builder->insertBatch()

Generates an insert string based on the data you supply, and runs thequery. You can either pass an array or an object to thefunction. Here is an example using an array:

  1. $data = [
  2. [
  3. 'title' => 'My title',
  4. 'name' => 'My Name',
  5. 'date' => 'My date'
  6. ],
  7. [
  8. 'title' => 'Another title',
  9. 'name' => 'Another Name',
  10. 'date' => 'Another date'
  11. ]
  12. ];
  13.  
  14. $builder->insertBatch($data);
  15. // Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')

The first parameter is an associative array of values.

Note

All values are escaped automatically producing safer queries.

Updating Data

$builder->replace()

This method executes a REPLACE statement, which is basically the SQLstandard for (optional) DELETE + INSERT, using PRIMARY and _UNIQUE_keys as the determining factor.In our case, it will save you from the need to implement complexlogics with different combinations of select(), update(),delete() and insert() calls.

Example:

  1. $data = [
  2. 'title' => 'My title',
  3. 'name' => 'My Name',
  4. 'date' => 'My date'
  5. ];
  6.  
  7. $builder->replace($data);
  8.  
  9. // Executes: REPLACE INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

In the above example, if we assume that the title field is our primarykey, then if a row containing ‘My title’ as the title value, that rowwill be deleted with our new row data replacing it.

Usage of the set() method is also allowed and all fields areautomatically escaped, just like with insert().

$builder->set()

This function enables you to set values for inserts or updates.

It can be used instead of passing a data array directly to the insertor update functions:

  1. $builder->set('name', $name);
  2. $builder->insert(); // Produces: INSERT INTO mytable (`name`) VALUES ('{$name}')

If you use multiple function called they will be assembled properlybased on whether you are doing an insert or an update:

  1. $builder->set('name', $name);
  2. $builder->set('title', $title);
  3. $builder->set('status', $status);
  4. $builder->insert();

set() will also accept an optional third parameter ($escape), thatwill prevent data from being escaped if set to FALSE. To illustrate thedifference, here is set() used both with and without the escapeparameter.

  1. $builder->set('field', 'field+1', FALSE);
  2. $builder->where('id', 2);
  3. $builder->update(); // gives UPDATE mytable SET field = field+1 WHERE `id` = 2
  4.  
  5. $builder->set('field', 'field+1');
  6. $builder->where('id', 2);
  7. $builder->update(); // gives UPDATE `mytable` SET `field` = 'field+1' WHERE `id` = 2

You can also pass an associative array to this function:

  1. $array = [
  2. 'name' => $name,
  3. 'title' => $title,
  4. 'status' => $status
  5. ];
  6.  
  7. $builder->set($array);
  8. $builder->insert();

Or an object:

  1. /*
  2. class Myclass {
  3. public $title = 'My Title';
  4. public $content = 'My Content';
  5. public $date = 'My Date';
  6. }
  7. */
  8.  
  9. $object = new Myclass;
  10. $builder->set($object);
  11. $builder->insert();

$builder->update()

Generates an update string and runs the query based on the data yousupply. You can pass an array or an object to the function. Hereis an example using an array:

  1. $data = [
  2. 'title' => $title,
  3. 'name' => $name,
  4. 'date' => $date
  5. ];
  6.  
  7. $builder->where('id', $id);
  8. $builder->update($data);
  9. // Produces:
  10. //
  11. // UPDATE mytable
  12. // SET title = '{$title}', name = '{$name}', date = '{$date}'
  13. // WHERE id = $id

Or you can supply an object:

  1. /*
  2. class Myclass {
  3. public $title = 'My Title';
  4. public $content = 'My Content';
  5. public $date = 'My Date';
  6. }
  7. */
  8.  
  9. $object = new Myclass;
  10. $builder->where('id', $id);
  11. $builder->update($object);
  12. // Produces:
  13. //
  14. // UPDATE `mytable`
  15. // SET `title` = '{$title}', `name` = '{$name}', `date` = '{$date}'
  16. // WHERE id = `$id`

Note

All values are escaped automatically producing safer queries.

You’ll notice the use of the $builder->where() function, enabling youto set the WHERE clause. You can optionally pass this informationdirectly into the update function as a string:

  1. $builder->update($data, "id = 4");

Or as an array:

  1. $builder->update($data, ['id' => $id]);

You may also use the $builder->set() function described above whenperforming updates.

$builder->updateBatch()

Generates an update 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:

  1. $data = [
  2. [
  3. 'title' => 'My title' ,
  4. 'name' => 'My Name 2' ,
  5. 'date' => 'My date 2'
  6. ],
  7. [
  8. 'title' => 'Another title' ,
  9. 'name' => 'Another Name 2' ,
  10. 'date' => 'Another date 2'
  11. ]
  12. ];
  13.  
  14. $builder->updateBatch($data, 'title');
  15.  
  16. // Produces:
  17. // UPDATE `mytable` SET `name` = CASE
  18. // WHEN `title` = 'My title' THEN 'My Name 2'
  19. // WHEN `title` = 'Another title' THEN 'Another Name 2'
  20. // ELSE `name` END,
  21. // `date` = CASE
  22. // WHEN `title` = 'My title' THEN 'My date 2'
  23. // WHEN `title` = 'Another title' THEN 'Another date 2'
  24. // ELSE `date` END
  25. // WHERE `title` IN ('My title','Another title')

The first parameter is an associative array of values, the second parameter is the where key.

Note

All values are escaped automatically producing safer queries.

Note

affectedRows() won’t give you proper results with this method,due to the very nature of how it works. Instead, updateBatch()returns the number of rows affected.

$builder->getCompiledUpdate()

This works exactly the same way as $builder->getCompiledInsert() exceptthat it produces an UPDATE SQL string instead of an INSERT SQL string.

For more information view documentation for $builder->getCompiledInsert().

Note

This method doesn’t work for batched updates.

Deleting Data

$builder->delete()

Generates a delete SQL string and runs the query.

  1. $builder->delete(['id' => $id]); // Produces: // DELETE FROM mytable // WHERE id = $id

The first parameter is the where clause.You can also use the where() or or_where() functions instead of passingthe data to the first parameter of the function:

  1. $builder->where('id', $id);
  2. $builder->delete();
  3.  
  4. // Produces:
  5. // DELETE FROM mytable
  6. // WHERE id = $id

If you want to delete all data from a table, you can use the truncate()function, or emptyTable().

$builder->emptyTable()

Generates a delete SQL string and runs thequery:

  1. $builder->emptyTable('mytable'); // Produces: DELETE FROM mytable

$builder->truncate()

Generates a truncate SQL string and runs the query.

  1. $builder->truncate();
  2.  
  3. // Produce:
  4. // TRUNCATE mytable

Note

If the TRUNCATE command isn’t available, truncate() willexecute as “DELETE FROM table”.

$builder->getCompiledDelete()

This works exactly the same way as $builder->getCompiledInsert() exceptthat it produces a DELETE SQL string instead of an INSERT SQL string.

For more information view documentation for $builder->getCompiledInsert().

Method Chaining

Method chaining allows you to simplify your syntax by connectingmultiple functions. Consider this example:

  1. $query = $builder->select('title')
  2. ->where('id', $id)
  3. ->limit(10, 20)
  4. ->get();

Resetting Query Builder

$builder->resetQuery()

Resetting Query Builder allows you to start fresh with your query withoutexecuting it first using a method like $builder->get() or $builder->insert().

This is useful in situations where you are using Query Builder to generate SQL(ex. $builder->getCompiledSelect()) but then choose to, for instance,run the query:

  1. // Note that the second parameter of the get_compiled_select method is FALSE
  2. $sql = $builder->select(['field1','field2'])
  3. ->where('field3',5)
  4. ->getCompiledSelect(false);
  5.  
  6. // ...
  7. // Do something crazy with the SQL code... like add it to a cron script for
  8. // later execution or something...
  9. // ...
  10.  
  11. $data = $builder->get()->getResultArray();
  12.  
  13. // Would execute and return an array of results of the following query:
  14. // SELECT field1, field1 from mytable where field3 = 5;

Class Reference

  • CodeIgniter\Database\BaseBuilder
resetQuery()
Returns:BaseBuilder instance (method chaining)
Return type:BaseBuilder

Resets the current Query Builder state. Useful when you wantto build a query that can be canceled under certain conditions.

countAllResults([$reset = TRUE])
Parameters:
  • $reset (bool) – Whether to reset values for SELECTs
Returns:

Number of rows in the query result

Return type:

int

Generates a platform-specific query string that countsall records returned by an Query Builder query.

countAll([$reset = TRUE])
Parameters:
  • $reset (bool) – Whether to reset values for SELECTs
Returns:

Number of rows in the query result

Return type:

int

Generates a platform-specific query string that countsall records returned by an Query Builder query.

get([$limit = NULL[, $offset = NULL[, $reset = TRUE]]]])
Parameters:
  • $limit (int) – The LIMIT clause
  • $offset (int) – The OFFSET clause
  • $reset (bool) – Do we want to clear query builder values?
Returns:

CodeIgniterDatabaseResultInterface instance (method chaining)

Return type:

CodeIgniterDatabaseResultInterface

Compiles and runs SELECT statement based on the alreadycalled Query Builder methods.

getWhere([$where = NULL[, $limit = NULL[, $offset = NULL[, $reset = TRUE]]]]])
Parameters:
  • $where (string) – The WHERE clause
  • $limit (int) – The LIMIT clause
  • $offset (int) – The OFFSET clause
  • $reset (bool) – Do we want to clear query builder values?
Returns:

CodeIgniterDatabaseResultInterface instance (method chaining)

Return type:

CodeIgniterDatabaseResultInterface

Same as get(), but also allows the WHERE to be added directly.

select([$select = '*'[, $escape = NULL]])
Parameters:
  • $select (string) – The SELECT portion of a query
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a SELECT clause to a query.

selectAvg([$select = ''[, $alias = '']])
Parameters:
  • $select (string) – Field to compute the average of
  • $alias (string) – Alias for the resulting value name
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a SELECT AVG(field) clause to a query.

selectMax([$select = ''[, $alias = '']])
Parameters:
  • $select (string) – Field to compute the maximum of
  • $alias (string) – Alias for the resulting value name
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a SELECT MAX(field) clause to a query.

selectMin([$select = ''[, $alias = '']])
Parameters:
  • $select (string) – Field to compute the minimum of
  • $alias (string) – Alias for the resulting value name
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a SELECT MIN(field) clause to a query.

selectSum([$select = ''[, $alias = '']])
Parameters:
  • $select (string) – Field to compute the sum of
  • $alias (string) – Alias for the resulting value name
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a SELECT SUM(field) clause to a query.

selectCount([$select = ''[, $alias = '']])
Parameters:
  • $select (string) – Field to compute the average of
  • $alias (string) – Alias for the resulting value name
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a SELECT COUNT(field) clause to a query.

distinct([$val = TRUE])
Parameters:
  • $val (bool) – Desired value of the “distinct” flag
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Sets a flag which tells the query builder to adda DISTINCT clause to the SELECT portion of the query.

from($from[, $overwrite = FALSE])
Parameters:
  • $from (mixed) – Table name(s); string or array
  • $overwrite (bool) – Should we remove the first table existing?
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Specifies the FROM clause of a query.

join($table, $cond[, $type = ''[, $escape = NULL]])
Parameters:
  • $table (string) – Table name to join
  • $cond (string) – The JOIN ON condition
  • $type (string) – The JOIN type
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a JOIN clause to a query.

where($key[, $value = NULL[, $escape = NULL]])
Parameters:
  • $key (mixed) – Name of field to compare, or associative array
  • $value (mixed) – If a single key, compared to this value
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance

Return type:

object

Generates the WHERE portion of the query.Separates multiple calls with ‘AND’.

orWhere($key[, $value = NULL[, $escape = NULL]])
Parameters:
  • $key (mixed) – Name of field to compare, or associative array
  • $value (mixed) – If a single key, compared to this value
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance

Return type:

object

Generates the WHERE portion of the query.Separates multiple calls with ‘OR’.

orWhereIn([$key = NULL[, $values = NULL[, $escape = NULL]]])
Parameters:
  • $key (string) – The field to search
  • $values (array|Closure) – Array of target values, or anonymous function for subquery
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance

Return type:

object

Generates a WHERE field IN(‘item’, ‘item’) SQL query,joined with ‘OR’ if appropriate.

orWhereNotIn([$key = NULL[, $values = NULL[, $escape = NULL]]])
Parameters:
  • $key (string) – The field to search
  • $values (array|Closure) – Array of target values, or anonymous function for subquery
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance

Return type:

object

Generates a WHERE field NOT IN(‘item’, ‘item’) SQL query,joined with ‘OR’ if appropriate.

whereIn([$key = NULL[, $values = NULL[, $escape = NULL]]])
Parameters:
  • $key (string) – Name of field to examine
  • $values (array|Closure) – Array of target values, or anonymous function for subquery
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance

Return type:

object

Generates a WHERE field IN(‘item’, ‘item’) SQL query,joined with ‘AND’ if appropriate.

whereNotIn([$key = NULL[, $values = NULL[, $escape = NULL]]])
Parameters:
  • $key (string) – Name of field to examine
  • $values (array|Closure) – Array of target values, or anonymous function for subquery
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance

Return type:

object

Generates a WHERE field NOT IN(‘item’, ‘item’) SQL query,joined with ‘AND’ if appropriate.

groupStart()
Returns:BaseBuilder instance (method chaining)
Return type:BaseBuilder

Starts a group expression, using ANDs for the conditions inside it.

orGroupStart()
Returns:BaseBuilder instance (method chaining)
Return type:BaseBuilder

Starts a group expression, using ORs for the conditions inside it.

notGroupStart()
Returns:BaseBuilder instance (method chaining)
Return type:BaseBuilder

Starts a group expression, using AND NOTs for the conditions inside it.

orNotGroupStart()
Returns:BaseBuilder instance (method chaining)
Return type:BaseBuilder

Starts a group expression, using OR NOTs for the conditions inside it.

groupEnd()
Returns:BaseBuilder instance
Return type:object

Ends a group expression.

like($field[, $match = ''[, $side = 'both'[, $escape = NULL[, $insensitiveSearch = FALSE]]]])
Parameters:
  • $field (string) – Field name
  • $match (string) – Text portion to match
  • $side (string) – Which side of the expression to put the ‘%’ wildcard on
  • $escape (bool) – Whether to escape values and identifiers
  • $insensitiveSearch (bool) – Whether to force a case-insensitive search
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a LIKE clause to a query, separating multiple calls with AND.

orLike($field[, $match = ''[, $side = 'both'[, $escape = NULL[, $insensitiveSearch = FALSE]]]])
Parameters:
  • $field (string) – Field name
  • $match (string) – Text portion to match
  • $side (string) – Which side of the expression to put the ‘%’ wildcard on
  • $escape (bool) – Whether to escape values and identifiers
  • $insensitiveSearch (bool) – Whether to force a case-insensitive search
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a LIKE clause to a query, separating multiple class with OR.

notLike($field[, $match = ''[, $side = 'both'[, $escape = NULL[, $insensitiveSearch = FALSE]]]])
Parameters:
  • $field (string) – Field name
  • $match (string) – Text portion to match
  • $side (string) – Which side of the expression to put the ‘%’ wildcard on
  • $escape (bool) – Whether to escape values and identifiers
  • $insensitiveSearch (bool) – Whether to force a case-insensitive search
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a NOT LIKE clause to a query, separating multiple calls with AND.

orNotLike($field[, $match = ''[, $side = 'both'[, $escape = NULL[, $insensitiveSearch = FALSE]]]])
Parameters:
  • $field (string) – Field name
  • $match (string) – Text portion to match
  • $side (string) – Which side of the expression to put the ‘%’ wildcard on
  • $escape (bool) – Whether to escape values and identifiers
  • $insensitiveSearch (bool) – Whether to force a case-insensitive search
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a NOT LIKE clause to a query, separating multiple calls with OR.

having($key[, $value = NULL[, $escape = NULL]])
Parameters:
  • $key (mixed) – Identifier (string) or associative array of field/value pairs
  • $value (string) – Value sought if $key is an identifier
  • $escape (string) – Whether to escape values and identifiers
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a HAVING clause to a query, separating multiple calls with AND.

orHaving($key[, $value = NULL[, $escape = NULL]])
Parameters:
  • $key (mixed) – Identifier (string) or associative array of field/value pairs
  • $value (string) – Value sought if $key is an identifier
  • $escape (string) – Whether to escape values and identifiers
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a HAVING clause to a query, separating multiple calls with OR.

orHavingIn([$key = NULL[, $values = NULL[, $escape = NULL]]])
Parameters:
  • $key (string) – The field to search
  • $values (array|Closure) – Array of target values, or anonymous function for subquery
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance

Return type:

object

Generates a HAVING field IN(‘item’, ‘item’) SQL query,joined with ‘OR’ if appropriate.

orHavingNotIn([$key = NULL[, $values = NULL[, $escape = NULL]]])
Parameters:
  • $key (string) – The field to search
  • $values (array|Closure) – Array of target values, or anonymous function for subquery
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance

Return type:

object

Generates a HAVING field NOT IN(‘item’, ‘item’) SQL query,joined with ‘OR’ if appropriate.

havingIn([$key = NULL[, $values = NULL[, $escape = NULL]]])
Parameters:
  • $key (string) – Name of field to examine
  • $values (array|Closure) – Array of target values, or anonymous function for subquery
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance

Return type:

object

Generates a HAVING field IN(‘item’, ‘item’) SQL query,joined with ‘AND’ if appropriate.

havingNotIn([$key = NULL[, $values = NULL[, $escape = NULL]]])
Parameters:
  • $key (string) – Name of field to examine
  • $values (array|Closure) – Array of target values, or anonymous function for subquery
  • $escape (bool) – Whether to escape values and identifiers
  • $insensitiveSearch (bool) – Whether to force a case-insensitive search
Returns:

BaseBuilder instance

Return type:

object

Generates a HAVING field NOT IN(‘item’, ‘item’) SQL query,joined with ‘AND’ if appropriate.

havingLike($field[, $match = ''[, $side = 'both'[, $escape = NULL[, $insensitiveSearch = FALSE]]]])
Parameters:
  • $field (string) – Field name
  • $match (string) – Text portion to match
  • $side (string) – Which side of the expression to put the ‘%’ wildcard on
  • $escape (bool) – Whether to escape values and identifiers
  • $insensitiveSearch (bool) – Whether to force a case-insensitive search
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a LIKE clause to a HAVING part of the query, separating multiple calls with AND.

orHavingLike($field[, $match = ''[, $side = 'both'[, $escape = NULL[, $insensitiveSearch = FALSE]]]])
Parameters:
  • $field (string) – Field name
  • $match (string) – Text portion to match
  • $side (string) – Which side of the expression to put the ‘%’ wildcard on
  • $escape (bool) – Whether to escape values and identifiers
  • $insensitiveSearch (bool) – Whether to force a case-insensitive search
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a LIKE clause to a HAVING part of the query, separating multiple class with OR.

notHavingLike($field[, $match = ''[, $side = 'both'[, $escape = NULL[, $insensitiveSearch = FALSE]]]])
Parameters:
  • $field (string) – Field name
  • $match (string) – Text portion to match
  • $side (string) – Which side of the expression to put the ‘%’ wildcard on
  • $escape (bool) – Whether to escape values and identifiers
  • $insensitiveSearch (bool) – Whether to force a case-insensitive search
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a NOT LIKE clause to a HAVING part of the query, separating multiple calls with AND.

orNotHavingLike($field[, $match = ''[, $side = 'both'[, $escape = NULL[, $insensitiveSearch = FALSE]]]])
Parameters:
  • $field (string) – Field name
  • $match (string) – Text portion to match
  • $side (string) – Which side of the expression to put the ‘%’ wildcard on
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a NOT LIKE clause to a HAVING part of the query, separating multiple calls with OR.

havingGroupStart()
Returns:BaseBuilder instance (method chaining)
Return type:BaseBuilder

Starts a group expression for HAVING clause, using ANDs for the conditions inside it.

orHavingGroupStart()
Returns:BaseBuilder instance (method chaining)
Return type:BaseBuilder

Starts a group expression for HAVING clause, using ORs for the conditions inside it.

notHavingGroupStart()
Returns:BaseBuilder instance (method chaining)
Return type:BaseBuilder

Starts a group expression for HAVING clause, using AND NOTs for the conditions inside it.

orNotHavingGroupStart()
Returns:BaseBuilder instance (method chaining)
Return type:BaseBuilder

Starts a group expression for HAVING clause, using OR NOTs for the conditions inside it.

havingGroupEnd()
Returns:BaseBuilder instance
Return type:object

Ends a group expression for HAVING clause.

groupBy($by[, $escape = NULL])
Parameters:
  • $by (mixed) – Field(s) to group by; string or array
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds a GROUP BY clause to a query.

orderBy($orderby[, $direction = ''[, $escape = NULL]])
Parameters:
  • $orderby (string) – Field to order by
  • $direction (string) – The order requested - ASC, DESC or random
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

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:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds LIMIT and OFFSET clauses to a query.

offset($offset)
Parameters:
  • $offset (int) – Number of rows to skip
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds an OFFSET clause to a query.

set($key[, $value = ''[, $escape = NULL]])
Parameters:
  • $key (mixed) – Field name, or an array of field/value pairs
  • $value (string) – Field value, if $key is a single field
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds field/value pairs to be passed later to insert(),update() or replace().

insert([$set = NULL[, $escape = NULL]])
Parameters:
  • $set (array) – An associative array of field/value pairs
  • $escape (bool) – Whether to escape values and identifiers
Returns:

TRUE on success, FALSE on failure

Return type:

bool

Compiles and executes an INSERT statement.

insertBatch([$set = NULL[, $escape = NULL[, $batch_size = 100]]])
Parameters:
  • $set (array) – Data to insert
  • $escape (bool) – Whether to escape values and identifiers
  • $batch_size (int) – Count of rows to insert at once
Returns:

Number of rows inserted or FALSE on failure

Return type:

mixed

Compiles and executes batch INSERT statements.

Note

When more than $batch_size rows are provided, multipleINSERT queries will be executed, each trying to insertup to $batch_size rows.

setInsertBatch($key[, $value = ''[, $escape = NULL]])
Parameters:
  • $key (mixed) – Field name or an array of field/value pairs
  • $value (string) – Field value, if $key is a single field
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds field/value pairs to be inserted in a table later via insertBatch().

update([$set = NULL[, $where = NULL[, $limit = NULL]]])
Parameters:
  • $set (array) – An associative array of field/value pairs
  • $where (string) – The WHERE clause
  • $limit (int) – The LIMIT clause
Returns:

TRUE on success, FALSE on failure

Return type:

bool

Compiles and executes an UPDATE statement.

updateBatch([$set = NULL[, $value = NULL[, $batch_size = 100]]])
Parameters:
  • $set (array) – Field name, or an associative array of field/value pairs
  • $value (string) – Field value, if $set is a single field
  • $batch_size (int) – Count of conditions to group in a single query
Returns:

Number of rows updated or FALSE on failure

Return type:

mixed

Compiles and executes batch UPDATE statements.

Note

When more than $batch_size field/value pairs are provided,multiple queries will be executed, each handling up to$batch_size field/value pairs.

setUpdateBatch($key[, $value = ''[, $escape = NULL]])
Parameters:
  • $key (mixed) – Field name or an array of field/value pairs
  • $value (string) – Field value, if $key is a single field
  • $escape (bool) – Whether to escape values and identifiers
Returns:

BaseBuilder instance (method chaining)

Return type:

BaseBuilder

Adds field/value pairs to be updated in a table later via updateBatch().

replace([$set = NULL])
Parameters:
  • $set (array) – An associative array of field/value pairs
Returns:

TRUE on success, FALSE on failure

Return type:

bool

Compiles and executes a REPLACE statement.

delete([$where = ''[, $limit = NULL[, $reset_data = TRUE]]])
Parameters:
  • $where (string) – The WHERE clause
  • $limit (int) – The LIMIT clause
  • $reset_data (bool) – TRUE to reset the query “write” clause
Returns:

BaseBuilder instance (method chaining) or FALSE on failure

Return type:

mixed

Compiles and executes a DELETE query.

  • increment($column[, $value = 1])

Parameters:

  1. - **$column** (_string_) The name of the column to increment
  2. - **$value** (_int_) The amount to increment the column by

Increments the value of a field by the specified amount. If the fieldis not a numeric field, like a VARCHAR, it will likely be replacedwith $value.

  • decrement($column[, $value = 1])

Parameters:

  1. - **$column** (_string_) The name of the column to decrement
  2. - **$value** (_int_) The amount to decrement the column by

Decrements the value of a field by the specified amount. If the fieldis not a numeric field, like a VARCHAR, it will likely be replacedwith $value.

  1. - <code>truncate</code>()[](#truncate)
  2. -

Returns:TRUE on success, FALSE on failureReturn 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.

  1. - <code>emptyTable</code>()[](#emptyTable)
  2. -

Returns:TRUE on success, FALSE on failureReturn type:bool

Deletes all records from a table via a DELETE statement.

  1. - <code>getCompiledSelect</code>([_$reset = TRUE_])[](#getCompiledSelect)
  2. -

Parameters:

  1. - **$reset** (_bool_) Whether to reset the current QB values or notReturns:

The compiled SQL statement as a stringReturn type:string

Compiles a SELECT statement and returns it as a string.

  1. - <code>getCompiledInsert</code>([_$reset = TRUE_])[](#getCompiledInsert)
  2. -

Parameters:

  1. - **$reset** (_bool_) Whether to reset the current QB values or notReturns:

The compiled SQL statement as a stringReturn type:string

Compiles an INSERT statement and returns it as a string.

  1. - <code>getCompiledUpdate</code>([_$reset = TRUE_])[](#getCompiledUpdate)
  2. -

Parameters:

  1. - **$reset** (_bool_) Whether to reset the current QB values or notReturns:

The compiled SQL statement as a stringReturn type:string

Compiles an UPDATE statement and returns it as a string.

  1. - <code>getCompiledDelete</code>([_$reset = TRUE_])[](#getCompiledDelete)
  2. -

Parameters:

  1. - **$reset** (_bool_) Whether to reset the current QB values or notReturns:

The compiled SQL statement as a stringReturn type:string

Compiles a DELETE statement and returns it as a string.