tags:

views:

52

answers:

4
+2  A: 

I see no problems with that code. Typically I would first trim(), then perform any validation required, and then mysql_escape() (saving the mysql_escape till the last possible moment. If the only validation you are going to do is to check for empty strings then I see no issue.

Ben Reisner
A: 

Use strlen() instead of empty() when you check for a 0 length string, with the empty function ...

The following things are considered to be empty:

* "" (an empty string)
* 0 (0 as an integer)
* "0" (0 as a string)
* NULL
* FALSE
* array() (an empty array)
* var $var; (a variable declared, but without a value in a class)

As you can see, not all these values are an empty string.

SquareRootOf2
A: 

You should use both. I also recommend using filter_var because it will sanitize data as well. There are also many other things to consider.

  • Usernames should probably only be letters and numbers
  • Emails should be in the proper format
  • You should trim() everything
Chacha102
+1  A: 

Yes and no.

The "yes" part

It's good to sanitize user input for SQL Injection. And since it won't affect an empty string, you won't generate any false positives or other side effects with this method.

The "no" part

Technically speaking, you don't want to filter data too early. I would trim first, check value, and THEN escape it for a query when you know the data is valid.

if ( isset( $_POST['submit'] ) )
{
  $username = trim( $_POST['username'] );

  if ( '' == $username )
  {
    die ( 'You need to enter a username.' );
  } else {
    mysql_query( sprintf(
        "INSERT INTO table (username) VALUES('%s')"
      , mysql_real_escape_string( $username )
    ) );
  }
}
Peter Bailey