Skip to content

Instantly share code, notes, and snippets.

@samdark
Created June 21, 2012 19:33
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save samdark/2967994 to your computer and use it in GitHub Desktop.
Save samdark/2967994 to your computer and use it in GitHub Desktop.
Yii: handy functions to use Yii with raw SQL
<?php
/**
* Escapes values
*
* @param array $values array of values to escape
* @return string string ready to be included into SQL statement
* @throws CException if one of the values isn't a scalar
*/
function escape($values)
{
$values = (array)$values;
$escaped = array();
foreach($values as $value) {
if(!is_scalar($value)) {
throw new CException('One of the values passed to values() is not a scalar.');
}
$escaped[] = Yii::app()->db->quoteValue($value);
}
return implode(', ', $escaped);
}
/**
* Creates a command. Examples:
*
* command('SELECT * FROM post WHERE id IN(%s)', array(1, 2, 3))->queryAll();
* command('SELECT id FROM post WHERE name = %s', 'Alexander')->queryScalar();
* command('SELECT * FROM post WHERE id = %d', 101)->queryRow();
*
* @param string $sql SQL statement. You can use sprintf tokens here.
* @param ... any number of additional arguments. These will be properly escaped
* and used to replace sprintf tokens.
* @return CDbCommand
*/
function command($sql)
{
$args = func_get_args();
array_shift($args);
if(!empty($args)) {
foreach($args as &$arg) {
$arg = escape($arg);
}
$sql = call_user_func_array('sprintf', array_merge(array($sql), $args));
}
return Yii::app()->db->createCommand($sql);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment