Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function mysql_safe_query() {
- $num_args = func_num_args();
- if ($num_args == 0) die('mysql_safe_query usage:
- mysql_safe_query(\'UPDATE people SET (name, number) VALUES ? WHERE name = ? or ?` = ?\',
- array(\'new name\', 5553475), \'old name\', \'custom field\', 5,);
- This will automatically expand the array and escape all variables included via a question mark.
- Adding either \', " or ` after ? will surround that argument with that delimiter, or subarguments in the case of arrays, unless it\'s a number. This is only\
- added for compability.');
- $query = func_get_arg(0);
- $queryBits = explode('?', $query);
- $query = $queryBits[0];
- $count = count($queryBits);
- $link = null;
- if ($num_args == $count) {
- } else if ($num_args == $count + 1) {
- $link = func_get_arg($num_args);
- $res_type = is_resource($link) ? get_resource_type($link) : gettype($link);
- if(strpos($res_type, 'mysql') === false) {
- die('Invalid database resource type: ' . $res_type);
- }
- } else die("Wrong number of arguments for tep_db_safe_query $count $num_args");
- for ($i = 1; $i < $count; ++$i) {
- $arg = func_get_arg($i);
- $delimiter = '\'';
- if (strstr('\'"`', $queryBits[$i][0])) {
- $delimiter = $queryBits[$i][0];
- $queryBits[$i] = substr($queryBits[$i], 1);
- }
- $replace = array('\\', $delimiter);
- $replaceWith = array('\\\\', '\\'.$delimiter);
- if (is_numeric($arg)) {
- $query .= $arg.$queryBits[$i];
- } else if (is_array($arg)) {
- $res = array();
- foreach ($arg as $data) {
- if (is_numeric($data)) {
- $res[] = $data;
- } else if (is_null($data)) {
- $res[] = 'NULL';
- } else $res[] = $delimiter.str_replace($replace, $replaceWith, $data).$delimiter;
- }
- $query .= '('.join(',', $res).')'.$queryBits[$i];
- } else if (is_null($arg)) {
- $query .= 'NULL'.$queryBits[$i];
- } else {
- $query .= $delimiter.str_replace($replace, $replaceWith, $arg).$delimiter.$queryBits[$i];
- }
- }
- if ($link != null)
- return tep_db_query($query, $link);
- else
- return tep_db_query($query);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement