note 102884 added to function.pg-query-params

From: Date: Sat, 12 Mar 2011 01:45:45 +0000
Subject: note 102884 added to function.pg-query-params
Groups: php.notes 
Request: Send a blank email to php-notes+get-177814@lists.php.net to get a copy of this message
In reply to the previous post, here is a different take on the solution I came up with independently a while ago with using array_map to escape/encode and call_user_func_array to add the values into the query itself using sprintf. It doesnt use the native $ that pg_query_params() does, but it is a bit cleaner code wise. See sprintf for more details on how to create the query string. <?php /** * Escapes input and makes a query string from args * * @param string $query - sql query string with sprintf * place holders for values - %d int, %u int unsigned, %f float, %s string * @param array $args - holds the parameters to be escaped for the query * @param bool $fullEscape - should we escape % and _ (not escaped due to LIKE clauses) * @return string query */ function escape($query, array $params, $fullEscape=false) { $params = array_map('utf8_encode', $params); $params = array_map('pg_escape_string', $params); $params = $fullEscape === true ? array_map('addcslashes', $params, array('%_')) : $params; array_unshift($params, $query); $query = call_user_func_array('sprintf', $params); return $query; } //example usage: $query = 'SELECT * FROM table WHERE int_value=%d AND string_value=%s'; $params = array(2, 'example_string'); $query = escape($query, $params); ?> ---- Server IP: 69.147.83.197 Probable Submitter: 99.159.251.106 ---- Manual Page -- http://www.php.net/manual/en/function.pg-query-params.php Edit -- https://master.php.net/note/edit/102884 Del: integrated -- https://master.php.net/note/delete/102884/integrated Del: useless -- https://master.php.net/note/delete/102884/useless Del: bad code -- https://master.php.net/note/delete/102884/bad+code Del: spam -- https://master.php.net/note/delete/102884/spam Del: non-english -- https://master.php.net/note/delete/102884/non-english Del: in docs -- https://master.php.net/note/delete/102884/in+docs Del: other reasons-- https://master.php.net/note/delete/102884 Reject -- https://master.php.net/note/reject/102884 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#177814) next »