PHP Functions

jan12345

Active Member
Joined
Jun 6, 2011
Messages
91
Reaction score
0
Location
Eloff
Thought it would be worth starting a discussion for php, It is sometimes frustrating even for a trained and qualified person to make sense of code, especially if the code your working on was written by someone else. This could be a place were you can share functions that helped you get by a bug of some sort.

Below is a simple function that would ensure that certain characters for example: single quotes (') inserted into a input type "text" field will not screw up your MySQL syntax when the inserted text get stored in the DB regardless of the php configuration of the production server.

Code:
	function mysql_prep_value( $value ) {
		$magic_quotes_active = get_magic_quotes_gpc();
		$new_enough_php = function_exists( "mysql_real_escape_string" );
		if ( $new_enough_php ) {
			if ( $magic_quotes_active ) {
				$value = stripslashes( $value );
			}
		} else {
			if ( !$magic_quotes_active ) {
				$value = addslashes( $value );
			}
		}
		return $value;
	}
Test it out and see!
 
I think the context would determine the appropriate function to use. There is,however, the saying that there is more than one way to kill the cat.

prep_mysql_value() is more light weight.
 
By the way, the function you posted appears to be missing a rather crucial call to mysql_real_escape_string.

I think it should be as follows:

Code:
	function mysql_prep_value( $value ) {
		$magic_quotes_active = get_magic_quotes_gpc();
		$new_enough_php = function_exists( "mysql_real_escape_string" );
		if ( $new_enough_php ) {
			if ( $magic_quotes_active ) {
				$value = stripslashes( $value );
			}
			[B][U]$value = mysql_real_escape_string($value);[/U][/B]
		} else {
			if ( !$magic_quotes_active ) {
				$value = addslashes( $value );
			}
		}
		return $value;
	}

You know what, you might be right.
 
Top
Sign up to the MyBroadband newsletter
X