Posted By

TimoZachi on 07/25/12


Tagged

sql function injection query queries like


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

tux-world


Prevent sql injection in LIKE queries


 / Published in: PHP
 

Function to prevent sql injection in Like queries, where the characters '_' and '%' can be dangerous.

  1. <?php
  2. function escapeLike($mysql, $data)
  3. {
  4. if(is_int($data) || is_float($data)) return $data;
  5.  
  6. $escaped = $mysql->real_escape_string($data);
  7. $find = array('%' => '\\%', '_' => '\\_');
  8. return strtr($escaped, $find);
  9. }
  10.  
  11. //Usage
  12.  
  13. $dangerous_input = '%My Name';
  14.  
  15. //$mysql has to be either an instance of mysql or mysqli
  16. $query = "SELECT * FROM tbl WHERE field LIKE '" . escapeLike($mysql, $dangerous_input) . "%'";
  17. echo $query; //Echoes: SELECT * FROM tbl WHERE field LIKE '\%My Name%'
  18. ?>

Report this snippet  

You need to login to post a comment.