Database expressions can be used to add unescaped SQL fragments to a Database_Query_Builder object.
For example, you can use an expression to generate a column alias:
// SELECT CONCAT(first_name, last_name) AS full_name
$query = DB::select([DB::expr('CONCAT(first_name, last_name)'), 'full_name']);
More examples are available on the Query Builder page
Class declared in MODPATH/database/classes/Database/Expression.php on line 3.
$_parametersNULL
$_valueNULL
Sets the expression string.
$expression = new Database_Expression('COUNT(users.id)');
string
$value
required - Raw SQL expression string array
$parameters
= array(0) - Unquoted parameter values void
public function __construct($value, $parameters = [])
{
// Set the expression string
$this->_value = $value;
$this->_parameters = $parameters;
}
Return the value of the expression as a string.
echo $expression;
string
public function __toString()
{
return $this->value();
}
Bind a variable to a parameter.
string
$param
required - Parameter key to replace byref mixed
$var
required - Variable to use $this
public function bind($param, & $var)
{
$this->_parameters[$param] = & $var;
return $this;
}
Compile the SQL expression and return it. Replaces any parameters with their given values.
mixed
$db
= NULL - Database instance or name of instance string
public function compile($db = null)
{
if (!is_object($db)) {
// Get the database instance
$db = Database::instance($db);
}
$value = $this->value();
if (!empty($this->_parameters)) {
// Quote all of the parameter values
$params = array_map([$db, 'quote'], $this->_parameters);
// Replace the values in the expression
$value = strtr($value, $params);
}
return $value;
}
Set the value of a parameter.
string
$param
required - Parameter key to replace mixed
$value
required - Value to use $this
public function param($param, $value)
{
$this->_parameters[$param] = $value;
return $this;
}
Add multiple parameter values.
array
$params
required - List of parameter values $this
public function parameters(array $params)
{
$this->_parameters = $params + $this->_parameters;
return $this;
}
Get the expression value as a string.
$sql = $expression->value();
string
public function value()
{
return (string) $this->_value;
}