Advertisement
adam-prescott

Database Sanitization

Nov 12th, 2011
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.67 KB | None | 0 0
  1. <?php
  2.  
  3. doQuery("SELECT * FROM `table` WHERE `column` = '%s';", $var);
  4.  
  5. /* Usage:
  6.  * This is written to block SQL Injections Very Effectively, all 'mysql_query()' commands
  7.  * should be replaced with this function.
  8.  *
  9.  * $DBQuery = doQuery("SELECT * FROM `TABLE` WHERE `username` = '%s' AND `password` = '%s';" ,$Username, $Password);
  10.  * The way the above works it it still returns the mysql_query() you expect, except it has
  11.  * been Sanitized.
  12.  *
  13.  * The query MUST be in double quotes like above, the '%s' represent the placeholder, the sanitized
  14.  * data will be placed. The next few options are your varibles and are inserted in the order the
  15.  * '%s' appears. E.G.
  16.  * doQuery("SELECT * `table` WHERE `Var1` = '%s' AND `Var2` = '%s' etc...", $Var1, $Var2, $Var3, etc...)
  17.  * The Same works with Insert Querys and other queries you need to input varibles.
  18.  */
  19.  
  20. function doQuery($query) {
  21.     $numParams = func_num_args();
  22.     $params = func_get_args();
  23.    
  24.     if($numParams > 1) {
  25.         for($i=1;$i<$numParams;$i++) {
  26.             $params[$i] = mysql_real_escape_string($params[$i]);
  27.         }
  28.         $query = call_user_func_array('sprintf', $params);
  29.     }
  30.     $result = @mysql_query($query);
  31.     if(!$result) {
  32.         throw new Exception('DB Class - doQuery: MySQL Error - '.mysql_error());
  33.     } else {
  34.         return $result;
  35.     }
  36. }
  37.  
  38.  
  39. $FName = "' or Bob"; // Imagine this is actually a $_POST and some is trying to inject.
  40. // what would actually be returned is \' or Bob
  41. $SQLQuery = doQuery("SELECT * FROM `users` WHERE `FirstName` = '%s';", $FName);
  42.  
  43. // This show you can just use it like a normal mysql_query()
  44. if($SQLQuery != false) {
  45.     while($row = mysql_fetch_assoc($SQLQuery)) {
  46.         echo $row['FirstName'];
  47.     }
  48. }
  49. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement