Mega Code Archive

 
Categories / Php / MySQL Database
 

Mysql escape string

A big hole in PHP's mysql support: the lack of mysql_escape_string function. Wondered what the easiest way of taking any zero-terminated string (i.e. one with single/double quotes, commas, special chars) and putting it in an SQL statement so it ALWAYS WORKS? Use this version of mysql_escape_string; based on the formal MySQL escape charater definition found at www.mysql.com. <?php function mysql_escape_string($s) { $sl=strlen($s); for ($a=0;$a<$sl;$a++) { $c=substr($s,$a,1); switch(ord($c)) { case 0: $c = "\\0"; break; case 10: $c = "\\n"; break; case 9: $c = "\\t"; break; case 13: $c = "\\r"; break; case 8: $c = "\\b"; break; case 39: $c = "\\'"; break; case 34: $c = """; break; case 92: $c = "\\\\"; break; case 37: $c = "\\%"; break; case 95: $c = "\\_"; break; } $s2.=$c; } return $s2; } ?> Example : ======== //put any chars you like in $un and $pw $sql=sprintf("insert into users (username, password) values(\"%s\",\"% s\")",mysql_escape_string($un), mysql_escape_string($pw));