0

guys how come whenever i click submit button on my form without any data in the textbox, it's saying echo 'Either your username, or email is already taken!'; . How come it still passes through this despite of the form not having any data? what could be the best explanation?

if(isset($_POST['username']) && isset($_POST['email']))
{
    $username = $_POST['username'];
    $email = $_POST['email'];

    $extract= mysql_query("SELECT * FROM users where username='$username'");

    $resultq = mysql_num_rows($extract);
    if($resultq > 0)
    {
       echo 'Either your username, or email is already taken!';
       return;
    }

}

Please hi'm stuck with this line for 12 hours, i can't seem to move on :(

Daryl
  • 51
  • 2
  • 5
  • 10
  • 1
    [Please, don't use `mysql_*` functions in new code](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the [red box](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which. If you choose PDO, [here is a good tutorial](http://j.mp/PoWehJ). **You are also wide open to [SQL injections](http://stackoverflow.com/q/60174)** – John Conde Aug 24 '13 at 03:59
  • best explanation? That you check what the content is of both variables $username and $email and check whether or not these exist in your DB – Jeroen Ingelbrecht Aug 24 '13 at 03:59

3 Answers3

2

isset renders true for empty string. it checks the existence of a variable. Here is a detailed explanation.

You should use if (trim($_POST['username']) != "")

DevZer0
  • 13,433
  • 7
  • 27
  • 51
0
if(isset($_POST['submit']))
{
    $username = $_POST['username'];
    $email = $_POST['email'];

    $extract= mysql_query("SELECT * FROM users where username='$username'");

    $resultq = mysql_num_rows($extract);
    if($resultq > 0)
    {
       echo 'Either your username, or email is already taken!';
       return;
    }

}
chirag ode
  • 950
  • 7
  • 15
0

You can also try !empty :

If you want to check both username OR email if already exist you also need to check email in select query

    if(!empty($_POST['username']) && !empty($_POST['email']))
    {
        $username = $_POST['username'];
        $email = $_POST['email'];

        $extract= mysql_query("SELECT * FROM users where username='$username' OR email='$email'");

        $resultq = mysql_num_rows($extract);
        if($resultq > 0)
        {
           echo 'Either your username, or email is already taken!';
           return false;
        }
        else
        {
            echo 'Accept';
            return true;
        }
    }
Devang Rathod
  • 6,650
  • 2
  • 23
  • 32