DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
PHP Clean String For Mysql
// Function to clean up a string before using it in a mysql query
function clean_for_mysql($string,$max_length) {
$in_string = ltrim($string);
$in_string = rtrim($in_string);
if (round($max_length) < 1) {
$max_length = 131072; // 128K
}
if (strlen($in_string) > $max_length) {
$new_string = substr($in_string,0,$max_length);
}
$new_string = mysql_real_escape_string($new_string);
return $new_string;
}






Comments
Snippets Manager replied on Sun, 2010/06/27 - 4:58pm
Snippets Manager replied on Fri, 2006/02/17 - 5:24am
Snippets Manager replied on Fri, 2006/02/10 - 8:57pm
Snippets Manager replied on Fri, 2006/02/17 - 12:37pm
clean_for_mysql("Hack String'", 12);Will return: Hack String\ (note the ending ' has been cut off) Which when put in an SQL Query will escape the closing quote and allow injection. MySQL will automatically cut your string to a certain length if you supply a limit for the field, so there is no need for the insecure substr(). Instead, just use:mysql_real_escape_string(trim($string))Snippets Manager replied on Fri, 2006/02/17 - 5:18am
$result = $db->query("SELECT * FROM job WHERE job_id IN(?, ?, ?)", array("one", "two", "three"));