Created
June 9, 2013 13:00
-
-
Save psdtohtml5/5743421 to your computer and use it in GitHub Desktop.
PHP: Prepare parameters for PDO Quries
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 | |
/** | |
* This function loops through the $_POST global and returns parameters that can be used in | |
* a PDO statement directly. Note : For this function to work properly the | |
* PDO::ATTR_EMULATE_PREPARES should be set to "false" | |
* like so "$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false)". | |
* @param Array $exclude This is an array of keys in $_POST that you want the function to ignore | |
* @return Array The function returns an array that can be used as parameters for the PDO statement | |
*/ | |
function get_params($exclude = array()) { | |
$keys = array(); | |
$values = array(); | |
$placeholder_keys = array(); | |
$params = array(); | |
foreach ($_POST as $key => $value) { | |
if(!in_array($key, $exclude)) { | |
$filtered_key = filter_var($key); | |
$keys[] = $filtered_key; | |
$placeholder_keys[] = ":" . $filtered_key; | |
if(is_array($value)){ | |
$value = implode(",", $value); | |
} | |
$values[] = $value; | |
} | |
} | |
$comma_sep_keys = implode(",", $keys); | |
$comma_sep_placeholder_keys = implode(",", $placeholder_keys); | |
$params['keys'] = $keys; | |
$params['values'] = $values; | |
$params['placeholder_keys'] = $placeholder_keys; | |
$params['comma_sep_keys'] = $comma_sep_keys; | |
$params['comma_sep_placeholder_keys'] = $comma_sep_placeholder_keys; | |
return $params; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment