0

is this the correct way to avoid SQL Injection in this SELECT?

// --[  Method  ]---------------------------------------------------------------
//
//  - Purpose   : Check if provided $email (taken from user input) exists in the DB
//
// -----------------------------------------------------------------------------
function DB_EmailExists($email)
{
    //
    if(DB_Connect() == false)
    {
        echo mysqli_error();
        return false;
    }

    //
    $stmt = $GLOBALS['global_db_link']->prepare("SELECT * FROM ".$GLOBALS['global_db_table_users']." WHERE Email=?");
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $stmt->store_result();
    $numrows = $stmt->num_rows;
    $stmt->close();

    //
    if ($numrows==0)
    {
        DB_Disconnect();
        return false;
    }

    //
    DB_Disconnect();

    return true;
}
PeeS
  • 1,105
  • 2
  • 17
  • 37
  • Almost. I would strongly suggest that you do NOT use $GLOBALS like that. Inject the database into this class, and call it directly (`$this->db_link->prepare(....`) – random_user_name Nov 28 '15 at 21:40
  • 1) why downvoted? 2) why not use $GLOBALS like that, any explanation ? – PeeS Nov 28 '15 at 21:48
  • 1
    Didn't downvote. And there's plenty of resources on why $GLOBALS is not good: http://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why and http://stackoverflow.com/questions/12445972/stop-using-global-in-php and http://stackoverflow.com/questions/8715897/why-is-it-considered-bad-practice-to-use-global-reference-inside-functions and https://tomnomnom.com/posts/why-global-state-is-the-devil-and-how-to-avoid-using-it and many others.... – random_user_name Nov 28 '15 at 21:53
  • Thanks, will have a look into this. – PeeS Nov 28 '15 at 21:54

1 Answers1

1

Yes, that works. But no need to SELECT *, just use SELECT email

VIDesignz
  • 4,435
  • 3
  • 23
  • 34
  • 1
    Perfect, i have added re-captcha to ensure no 'bot' is submitting the POST too. – PeeS Nov 28 '15 at 21:42
  • @Pees - captchas are not foolproof, and they are bad for user experience. It's better to use other techniques to prevent bots. http://stackoverflow.com/a/13158804/870729 as well as using a nonce: http://stackoverflow.com/questions/4145531/how-to-create-and-use-nonces – random_user_name Nov 28 '15 at 21:55
  • @cale_b Google's no-captcha is pretty legit though. – VIDesignz Nov 28 '15 at 21:57