Prevent SQL Injection


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

Pass a user-inputted variable to this function in order to prevent SQL injection. Example:

mysql_query("INSERT INTO table VALUES('" . sql_sanitize($_POST["variable") . "')");

Instead of:

mysql_query("INSERT INTO table VALUES('" . $_POST["variable"] . "'");


Copy this code and paste it in your HTML
  1. /*
  2. Function: sql_sanitize( $sCode )
  3. Description: "Sanitize" a string of SQL code to prevent SQL injection.
  4. Parameters: $sCode
  5. The SQL code which you wish to sanitize.
  6. Example: mysql_query('UPDATE table SET value="' . sql_sanitize("' SET id='4'") . '" WHERE id="1"');
  7. Requirements: PHP version 4 or greater
  8. Notes:
  9. Author: engel <[email protected]>
  10. */
  11. function sql_sanitize( $sCode ) {
  12. if ( function_exists( "mysql_real_escape_string" ) ) { // If PHP version > 4.3.0
  13. $sCode = mysql_real_escape_string( $sCode ); // Escape the MySQL string.
  14. } else { // If PHP version < 4.3.0
  15. $sCode = addslashes( $sCode ); // Precede sensitive characters with a backslash \
  16. }
  17. return $sCode; // Return the sanitized code
  18. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.