Return to Snippet

Revision: 4333
at November 28, 2007 18:56 by engel


Updated Code
/*
Function:	sql_sanitize( $sCode )
Description:	"Sanitize" a string of SQL code to prevent SQL injection.
Parameters:	$sCode
			The SQL code which you wish to sanitize.
Example:	mysql_query('UPDATE table SET value="' . sql_sanitize("' SET id='4'") . '" WHERE id="1"');
Requirements:	PHP version 4 or greater
Notes:		
Author:		engel <[email protected]>
*/
function sql_sanitize( $sCode ) {
	if ( function_exists( "mysql_real_escape_string" ) ) {		// If PHP version > 4.3.0
		$sCode = mysql_real_escape_string( $sCode );		// Escape the MySQL string.
	} else { // If PHP version < 4.3.0
		$sCode = addslashes( $sCode );				// Precede sensitive characters with a backslash \
	}
	return $sCode;							// Return the sanitized code
}

Revision: 4332
at November 28, 2007 09:27 by engel


Updated Code
/*
Function: sql_sanitize( $sCode )
Description: "Sanitize" a string of SQL code to prevent SQL injection.
Parameters: $sCode: The SQL code which you wish to sanitize.
Example: mysql_query('UPDATE table SET value="' . sql_sanitize("' SET id='4'") . '" WHERE id="1"');
Requirements: PHP version 4 or greater
Notes: 
*/
function sql_sanitize( $sCode ) {
	if ( function_exists( "mysql_real_escape_string" ) ) { // If PHP version > 4.3.0
		$sCode = mysql_real_escape_string( $sCode ); // Escape the MySQL string.
	} else { // If PHP version < 4.3.0
		$sCode = addslashes( $sCode ); // Precede sensitive characters with a backslash \
	}
	return $sCode; // Return the sanitized code
}

Revision: 4331
at November 28, 2007 09:25 by engel


Initial Code
/*
Function:				sql_sanitize( $sCode )
Description:			"Sanitize" a string of SQL code to prevent SQL injection.
Parameters:			$sCode
						The SQL code which you wish to sanitize.
Example:				mysql_query('UPDATE table SET value="' . sql_sanitize("' SET id='4'") . '" WHERE id="1"');
Requirements:			PHP version 4 or greater
*/
function sql_sanitize( $sCode ) {
	if ( function_exists( "mysql_real_escape_string" ) ) {				// If PHP version > 4.3.0
		$sCode = mysql_real_escape_string( $sCode );				// Escape the MySQL string.
	} else {													// If PHP version < 4.3.0
		$sCode = addslashes( $sCode );							// Precede sensitive characters with a slash \
	}
	return $sCode;											// Return the sanitized code
}

Initial URL

                                

Initial Description
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"] . "'");

Initial Title
Prevent SQL Injection

Initial Tags
sql, function

Initial Language
PHP