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

Snippets has posted 5883 posts at DZone. View Full User Profile

PHP Clean String For Mysql

  • submit to reddit
        // 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;


Snippets Manager replied on Sun, 2010/06/27 - 4:58pm

Bug. If $in_string length is less than $max_length then the string is never set to $new_string. Simple fix: if (strlen($in_string) > $max_length) { $new_string = substr($in_string,0,$max_length); } else { $new_string = $in_string }

Snippets Manager replied on Fri, 2006/02/17 - 5:24am

Security hole fixed... I moved the mysql_escape_string to be the last thing applied to the string.

Snippets Manager replied on Fri, 2006/02/10 - 8:57pm

PEAR DB, MySql and MySqli all define functions to escape strings that you are passing in as parameters and quote string that you are using for identifiers. (Table, View and Field names etc. etc) Use them.

Snippets Manager replied on Fri, 2006/02/17 - 12:37pm

This function introduces a big security hole. For example: 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

Why not rely on PEAR::DB to magically do it for you? $result = $db->query("SELECT * FROM job WHERE job_id IN(?, ?, ?)", array("one", "two", "three"));