Return to Snippet

Revision: 58616
at July 25, 2012 08:37 by TimoZachi


Initial Code
<?php
function escapeLike($mysql, $data)
{
	if(is_int($data) || is_float($data)) return $data;
	
	$escaped = $mysql->real_escape_string($data);
	$find = array('%' => '\\%', '_' => '\\_');
	return strtr($escaped, $find);
}

//Usage

$dangerous_input = '%My Name';

//$mysql has to be either an instance of mysql or mysqli
$query = "SELECT * FROM tbl WHERE field LIKE '" . escapeLike($mysql, $dangerous_input) . "%'";
echo $query; //Echoes: SELECT * FROM tbl WHERE field LIKE '\%My Name%'
?>

Initial URL

                                

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

Initial Title
Prevent sql injection in LIKE queries

Initial Tags
sql, function, query

Initial Language
PHP