Advertisement
Guest User

mysql_safe_query

a guest
Feb 7th, 2012
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.11 KB | None | 0 0
  1. function mysql_safe_query() {
  2.   $num_args = func_num_args();
  3.   if ($num_args == 0) die('mysql_safe_query usage:
  4. mysql_safe_query(\'UPDATE people SET (name, number) VALUES ? WHERE name = ? or ?` = ?\',
  5.     array(\'new name\', 5553475), \'old name\', \'custom field\', 5,);
  6.  
  7. This will automatically expand the array and escape all variables included via a question mark.
  8. 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\
  9. added for compability.');
  10.   $query = func_get_arg(0);
  11.   $queryBits = explode('?', $query);
  12.   $query = $queryBits[0];
  13.   $count = count($queryBits);
  14.   $link = null;
  15.   if ($num_args == $count) {
  16.   } else if ($num_args == $count + 1) {
  17.     $link = func_get_arg($num_args);
  18.     $res_type = is_resource($link) ? get_resource_type($link) : gettype($link);
  19.     if(strpos($res_type, 'mysql') === false) {
  20.       die('Invalid database resource type: ' . $res_type);
  21.     }
  22.   } else die("Wrong number of arguments for tep_db_safe_query $count $num_args");
  23.   for ($i = 1; $i < $count; ++$i) {
  24.     $arg = func_get_arg($i);
  25.     $delimiter = '\'';
  26.     if (strstr('\'"`', $queryBits[$i][0])) {
  27.       $delimiter = $queryBits[$i][0];
  28.       $queryBits[$i] = substr($queryBits[$i], 1);
  29.     }
  30.     $replace = array('\\', $delimiter);
  31.     $replaceWith = array('\\\\', '\\'.$delimiter);
  32.     if (is_numeric($arg)) {
  33.       $query .= $arg.$queryBits[$i];
  34.     } else if (is_array($arg)) {
  35.       $res = array();
  36.       foreach ($arg as $data) {
  37.         if (is_numeric($data)) {
  38.           $res[] = $data;
  39.         } else if (is_null($data)) {
  40.           $res[] = 'NULL';
  41.         } else $res[] = $delimiter.str_replace($replace, $replaceWith, $data).$delimiter;
  42.       }
  43.       $query .= '('.join(',', $res).')'.$queryBits[$i];
  44.     } else if (is_null($arg)) {
  45.       $query .= 'NULL'.$queryBits[$i];
  46.     } else {
  47.       $query .= $delimiter.str_replace($replace, $replaceWith, $arg).$delimiter.$queryBits[$i];
  48.     }
  49.   }
  50.   if ($link != null)
  51.     return tep_db_query($query, $link);
  52.   else
  53.     return tep_db_query($query);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement