-2

I am trying to create a registration page and throw an error when the username or the email exists but it doesn't catch the error. The table name in the database is 'users', username is 'uname' and email is 'email'. It inserts the data without a problem. I am using the same array to catch if any field is empty, also they are working perfectly fine.

        $query_usr = mysql_query("SELECT * FROM users WHERE uname='$uname' OR email='$email'");
                if ($query_usr["uname"] === $uname) {
          array_push($errors, "Username already exists");
        }
        if ($query_usr["email"] === $email) {
          array_push($errors, "email already exists");
        }
    if (count($err) == 0) {
            $pass = md5($pass1);
            $query = "INSERT INTO users (uname, email, password) VALUES('$uname', '$email', '$pass')";
            mysqli_query($connection, $query);

            $_SESSION["uname"] = $uname;
            $_SESSION["success"] = "You are now logged in";
            //header('location: index.php');
    }
    else{
        foreach ($err as $er){
            echo $er;
            echo "<p> </p>";
        }
    }
aioxie
  • 1
  • 1
  • 1
    How do you retrieve $uname and $email. PS you're open to SQL injection. PPS check a typo : $err is maybe $errors – Sfili_81 Nov 23 '18 at 13:40
  • Every time you use [the `mysql_`](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) database extension in new code **[this happens](https://media.giphy.com/media/kg9t6wEQKV7u8/giphy.gif)** it is deprecated and has been for years and is gone for ever in PHP7.0+. If you are just learning PHP, spend your energies learning the `PDO` or `mysqli` database extensions and prepared statements. [Start here](http://php.net/manual/en/book.pdo.php) – RiggsFolly Nov 23 '18 at 13:41
  • `mysql_*` functions are `depreciated you should use `mysqli_*` or pdo with prepared statements... u need to select userid where email or username = supplied then return results if you have results then it exists – Masivuye Cokile Nov 23 '18 at 13:41
  • 2
    Please dont __roll your own__ password hashing, specially not using MD5() or SHA1(). PHP provides [`password_hash()`](http://php.net/manual/en/function.password-hash.php) and [`password_verify()`](http://php.net/manual/en/function.password-verify.php) please use them. And here are some [good ideas about passwords](https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet) If you are using a PHP version prior to 5.5 [there is a compatibility pack available here](https://github.com/ircmaxell/password_compat) – RiggsFolly Nov 23 '18 at 13:42

1 Answers1

-1

Change From

if (count($err) == 0) {

To

if (count($errors) == 0) {

Also change following code like this in else part

foreach ($errors as $er){
            echo $er;
            echo "<p> </p>";
        }
Sadikhasan
  • 18,365
  • 21
  • 80
  • 122