Prevent sql injection in LIKE queries


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.