Last active
December 16, 2015 19:00
-
-
Save joelstein/5482015 to your computer and use it in GitHub Desktop.
Condensed function for injecting arguments into SQL query, properly escaped and quoted. Uses recursive anonymous function for nested arguments.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Returns query with escaped args injected into query. | |
* | |
* @param string $sql The query string. | |
* @param array $args The arguments to escape, quote, and inject into the query. | |
*/ | |
function query($sql, $args = array()) { | |
$quote = function($value) use (&$quote) { | |
return is_array($value) ? '(' . join(', ', array_map($quote, $value)) . ')' : ( | |
is_numeric(is_numeric($value)) ? $value : ( | |
is_bool($value) ? intval($value) : ( | |
is_null($value) ? 'NULL' : "'" . mysql_escape_string($value) . "'" ))); | |
}; | |
return strtr($sql, array_map($quote, $args)); | |
} | |
echo query("SELECT * FROM table WHERE id = :id AND title = :title AND published = :published AND color IN :colors", array( | |
':id' => 3, | |
':title' => 'title', | |
':published' => TRUE, | |
':colors' => array( | |
'blue', | |
'red', | |
), | |
)); | |
// Returns a query of: | |
// SELECT * FROM table WHERE id = '3' AND title = 'title' AND published = 1 AND color IN ('blue', 'red') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment