Created
November 8, 2012 01:35
-
-
Save jasonrhodes/4035909 to your computer and use it in GitHub Desktop.
SQL placeholder replacement
This file contains 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 | |
# for when you need to print out a PDO prepared statement or similar with ":symbol" style placeholders | |
function pdoprint($sql, $values) | |
{ | |
return preg_replace_callback( | |
'/:[^\s;)]*/', | |
function ($matches) use (&$values) { | |
return "'" . array_shift($values) . "'"; | |
}, | |
$sql | |
); | |
} | |
$sql = "SELECT * FROM users WHERE username = :name AND last_login > :last_login"; | |
$values = array(":name" => "jsmith2", ":last_login" => "2012-08-05"); | |
echo pdoprint($sql, $values); # => SELECT * FROM users WHERE username = jsmith2 AND last_login > 2012-08-05 | |
echo "<br><br>"; | |
# You could also run the $placeholders array through a flattener to account for single-level lists | |
function flatten($values) | |
{ | |
return array_map(function ($v) { | |
if (is_array($v)) { | |
$v = implode("','", $v); | |
} | |
return $v; | |
}, $values); | |
} | |
$sql = "SELECT * FROM users WHERE role IN (:roles) AND first_name = :first_name"; | |
$values = array(":roles" => array("admin", "contributor"), ":first_name" => "leslie"); | |
echo pdoprint($sql, flatten($values)); # => SELECT * FROM users WHERE role IN ('admin','contributor') AND first_name = 'leslie' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment