Page 1 of 1

Writing a function to clean form input

Posted: Thu Oct 27, 2011 10:11 am
by mikeashfield
How do you go about writing a function that:

1. Removes all spaces.
2. Replaces anything other than a number with nothing ('').
3. removes any decimal input (i.e. if 1302.921 is passed then return just 1302).
4. mysql_real_escape_string()'s the variable.

This may not be practical or may sound a bit simple but, I just am struggling to see where and how from tutorials on Google that you pass variables from your code to a function. 8O

Re: Writing a function to clean form input

Posted: Thu Oct 27, 2011 10:33 am
by Celauran
Impractical indeed. Since you asked:

Code: Select all

function whatever($db, $foo)
{
    $foo = preg_replace("/\s/", "", $foo);
    $foo = preg_replace("/(\d)?\.(\d)*/", '\\1', $foo);
    $foo = preg_replace("/[^0-9]/", "", $foo);
    $foo = mysqli_real_escape_string($db, $foo);
    return $foo;
}
Note I don't recommend actually using this or anything like it.

Re: Writing a function to clean form input

Posted: Thu Oct 27, 2011 10:37 am
by mikeashfield
Seeing as you were so kind as to reply, do you mind telling me why it would be impractical? :)

And just to clear something up, is $foo a variable that I assign the value to outside the function? Do functions ignore code outside the {}'s?

Re: Writing a function to clean form input

Posted: Thu Oct 27, 2011 10:46 am
by Celauran
is $foo a variable that I assign the value to outside the function?
$db and $foo are arguments you pass into the function, yes. $db is the database connection required for mysqli_real_escape_string() and $foo is the string you want "cleaned".

Code: Select all

$db = mysqli_connect($host, $username, $password, $database);
$string_to_be_cleaned = "Blah blah whatever";
$cleaned_string = whatever($db, $string_to_be_cleaned);
Do functions ignore code outside the {}'s?
Yes. The entirety of the function is contained within the braces. Anything not explicitly passed in will be out of scope.

Re: Writing a function to clean form input

Posted: Thu Oct 27, 2011 10:49 am
by mikeashfield
Celauran wrote:Impractical indeed.
What did you mean by this?

Re: Writing a function to clean form input

Posted: Thu Oct 27, 2011 11:19 am
by Celauran
It almost surely violates the DRY Principle. The function you described in your OP will be useful in a handful of cases, and you'll likely have to write a number of similar functions to deal with other similar but not identical cases. What if you want to keep decimal places sometimes? I can certainly imagine cases where removing spaces but not removing non-numeric characters would be useful, so that may do better as a standalone function. Removing decimals then trying to truncate your number won't work; removing decimals after you've truncated a number is pointless. You should typecast numbers rather than escaping them. In any case, the need to use mysql(i)_real_escape_string is obviated when using prepared statements.