Suggested articles for you:

60 thoughts on “PHP Login Form using MySQL

  1. blankAbiodun Awowole

    working with xampp environment, when the sign in form is click to sign in it shows my php code(” . $passwordError . “”; ?> ” . $noValid . “”; ?>) on below the enter password. And when i click on sign up it also show my php code on email box() and name box it shows (). kindly help. Thanks

    Reply
    1. blankRavi Bandakkanavar Post author

      Abiodun,

      Do you have access to the Database server? Could you please login and check whether the registered user details are present in the database?
      I hope you have configured the correct database user details in the connection file.

      Reply
  2. blankSarvesh

    Heyy!!!
    How to get the username, port of the mysql server.

    Reply
    1. blankRavi Bandakkanavar Post author

      Hi
      By default, it will be root or no username in some cases. You need to set the username manually in such cases.
      For MySQL the default port is 3306. During installation, you get an option to update it even.
      You can check all the configuration details in conf file.

      Reply
  3. blankAditi

    Notice: Undefined variable: db in C:\xampp\htdocs\OPTRA\login.php on line 18

    Fatal error: Call to a member function prepare() on null in C:\xampp\htdocs\OPTRA\login.php on line 18

    Reply
    1. blankRavi

      Hi,

      Please check what name field are you using for “username” in LoginForm.php.

      Username:

      Reply
  4. blankWycliff

    Yes I created a table ‘PROFILE’ and insterted USERNAME as ‘wycliff’ and PASSWORD as ‘1234’ and I am runing it in a xampp environment. It still gives me the errors

    Reply
    1. blankRavi Bandakkanavar Post author

      In order to login to a system, you need to register the user first.
      Use the below links to do the user registration.
      https://krazytech.com/programs/php-mysql-registration-form
      https://krazytech.com/programs/complete-login-and-registration-application-using-php-and-mysql – Combined registration and login application.

      Also, the default MySQL setup of xampp has a username as ‘root’ and the password would be null. Either set the password for MySQL user or remove the password configuration in the DBConnection.php file.

      Reply
  5. blankWycliff

    I am getting this error when I try to log in.
    Warning: mysqli_connect(): (HY000/1045): Access denied for user ‘root’@’localhost’ (using password: YES) in C:\xampp\htdocs\DBConnection.php on line 11

    Fatal error: Uncaught Error: Call to a member function prepare() on boolean in C:\xampp\htdocs\Login.php:18 Stack trace: #0 {main} thrown in C:\xampp\htdocs\Login.php on line 18

    kindly help

    Reply
    1. blankRavi Bandakkanavar Post author

      This is because of your MySQL credentials mismatch.
      Please set the username and password details in DBConnection.php as per your local MySQL setup.

      Reply
  6. blankCalvin Andrean

    Its still show me the incorrect password although i registered it to RegisterForm.php Can you help me?

    Reply
  7. blankYoung India

    Warning: mysqli_connect(): (HY000/1049): Unknown database ‘profiles’ in C:\xampp\htdocs\test-db-connection\DBConnection.php on line 10

    Fatal error: Uncaught Error: Call to a member function prepare() on boolean in C:\xampp\htdocs\test-db-connection\Login.php:21 Stack trace: #0 {main} thrown in C:\xampp\htdocs\test-db-connection\Login.php on line 21

    Reply
    1. blankRavi Bandakkanavar Post author

      Hi,

      First thing is to verify your DB Name and credentials, next, the field names that you have given in the input form. If you correct these things, it should work for you.

      Reply
  8. blankmuhammad

    hello sir i did everything but it keeps showing me incorrect password or username and it in my database all okk

    Reply
      1. blankmuhammad

        hello,

        i did the registration form in registered successful it also showed in my database but it still shows incorrect or password

        Reply
        1. blankRavi Bandakkanavar Post author

          Hi,

          It is case sensitive. Do verify it.
          Add another user and try logging in with the same. It is a tested application. It should work properly.

        2. blankmuhammad

          hello sir
          i honestly did that also is there a way i can send it to you so you can check ?

  9. blankkulwinder

    plz the login form which insert the query and select query

    Reply
  10. blankabhishekkrjha

    hey sir,
    im trying to login and it is showing incorrect username or password same as shreya is asked above…. im not finding any solution..dont know why… will you plz tell me? even everything is correct:- username, password, database and table

    Reply
      1. blankChethan Gowda

        hey sir,
        im trying to login and it is showing incorrect username or password same…. im not finding any solution..dont know why… will you plz tell me? even everything is correct:- username, password, database and table

        Reply
        1. blankRavi Bandakkanavar Post author

          Hi,

          How did you store your password in the database?
          The password should be in the encrypted format otherwise you need to remove this method – password_verify($inPassword, $PasswordDB)

          Let me know if it still does not work.

  11. blankvinoth

    hi sir i m a fresher of php….the above coding i was try but the output don’t go to userprofile page???can you explain to me

    Reply
  12. blankVignesh Iyer

    HEllon sir
    The explanation was good and easy to understand.
    But my problem is I am using php with oracle database. Can u pls help me in designing the login form as per oracle database requirement as I am new to php

    Reply
    1. blankRavi Bandakkanavar Post author

      Hi Vignesh,

      You can replace DBConnection.php with the following.
      $db= oci_connect(“user”, “password”, “//Host:Port/Database_name”);

      Once, the database connection is successful, use following statement to execute a query.

      $stmt = oci_parse($db, “SELECT USERNAME, PASSWORD FROM PROFILE WHERE USERNAME = ?”);

      I will write a post but it will take time.

      Reply
  13. blankVanjani

    excellent and simple but what if we need three to verify three parameters to match database username password center would it b e like this
    $stmt= $db->prepare(“SELECT username, password,center FROM data WHERE username = ?”); //Fetching all the records with input credentials
    $stmt->bind_param(“s”, $inUsername); //bind_param() – Binds variables to a prepared statement as parameters. “s” indicates the type of the parameter.
    $stmt->execute();
    $stmt->bind_result($UsernameDB, $PasswordDB, $Center ); // Binding i.e. mapping database results to new variables
    //Compare if the database has username and password entered by the user. Password has to be decrypted while comparing.
    if ($stmt->fetch() && password_verify($inPassword, $PasswordDB))

    Reply
    1. blankRavi Bandakkanavar Post author

      Vanjani,

      Why do you want to compare the third variable?
      the if condition should also be modified to
      if ($stmt->fetch() && password_verify($inPassword, $PasswordDB) && ($inCenter == $Center))

      Reply
  14. blankPrem Kumar

    Hai ravi,

    I need to login and display exsits if password and username is correct in db. Kindly help pls i am new to php

    0)
    {
    echo “Exists”;
    }
    else
    echo “Doesn’t exist”;
    }
    }
    ?>

    Reply
    1. blankRavi Bandakkanavar Post author

      Hi Prem,

      You can use the same code as is and replace the following lines in Login.php with echo statements.

      if ($stmt->fetch() && password_verify($inPassword, $PasswordDB))
      {
      echo “Exists”;
      }
      else
      {
      }

      Reply
      1. blankPrem Kumar

        Thanx sir,
        I have tried another code and its working.
        Kindly support in my future coding also as i am a beginner

        Reply
  15. blankamani

    prepare(“INSERT INTO profile(FULLNAME, EMAIL, USERNAME, PASSWORD CPASSWORD) VALUES(?, ?, ?, ?)”); //Fetching all the records with input credentials $stmt->bind_param(“ssss”, $inFullname, $inEmail, $inUsername, $encryptPassword,$encryptCPassword); //Where s indicates string type. You can use i-integer, d-double $stmt->execute(); $result = $stmt->affected_rows; $stmt -> close(); $db -> close(); if($result > 0) { header(“location: RegSuccess.php”); // user will be taken to the success page } else { echo “Oops. Something went wrong. Please try again”; ?> Try Login
    how can i resolve this problem sir…

    Reply
  16. blankJose Lopez

    Hi Ravi,
    Don’t know if this is happening with anyone else, but the Login.php page will not redirect to the UserProfile.php unless the HTML sections are removed. I removed the HTML tags and that did the trick. I found the fix here at https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php.
    Hope this helps anyone that ends up with a white page after submitting the LoginForm.php.
    That being said, thank you for this code.. saved me lots of work.
    -Jose

    Reply
  17. blankShreya

    Sir,
    I had already entered the data by mysql query, by not creating any registration file. But still to check whether the data is getting inserted or not, I created a registration file.But the same problem is happening with this too. The ‘register.php’ page has been showing as blank.
    Sir, is there any alternative option for this section?

    $stmt= $db->prepare(“SELECT USERNAME, PASSWORD FROM PROFILE WHERE USERNAME = ?”); //Fetching all the records with input credentials
    $stmt->bind_param(“s”, $inUsername); //You need to specify values to each ‘?’ explicitly while using prepared statements
    $stmt->execute();
    $stmt->bind_result($UsernameDB, $PasswordDB); // Binding i.e. mapping database results to new variables

    //Compare if the database has username and password entered by the user. Password has to be decrpted while comparing.
    if ($stmt->fetch() && password_verify($inPassword, $PasswordDB))
    {
    $_SESSION[‘username’]=$inUsername; //Storing the username value in session variable so that it can be retrieved on other pages
    header(“location: UserProfile.php”); // user will be taken to profile page
    }
    else
    {
    echo “Incorrect username or password”;
    ?>
    Login
    <?php
    }

    Reply
    1. blankRavi Bandakkanavar Post author

      Shreya,

      You can replace the line
      if ($stmt->fetch() && password_verify($inPassword, $PasswordDB)) with if($stmt->fetch()) and test.
      If that works, then try if($stmt->fetch() && $inPassword=$PasswordDB).

      You can type echo "Password = " . $PasswordDB; and check what value is returned.
      —————————————————
      Your register.php is not working fine hence you are not being taken to the next level. Hope you are executing this in WAMP environment.

      Reply
        1. blankRavi Bandakkanavar Post author

          Line 20 of Login.php?
          It’s the following line.

          $stmt= $db->prepare("SELECT USERNAME, PASSWORD FROM PROFILE WHERE USERNAME = ?");

          The reason could be your table. Did you create the table PROFILE with the same column names?

    2. blankabhishek jha

      hey shreya
      im facing same problem….have you find the solution?

      Reply
  18. blankShreya

    hello sir,
    my login.php page has been showing incorrect username and password even if I login with the correct username and password mentioned in the database. Can you help with this?

    Reply
  19. blankNick Tate

    Hi Ravi,
    Thank you very much for your excellent tutorial. I’m running it on a Raspberry Pi 3.

    There is just one little error in the “Logout.php” file.
    The line “mysql_close($connection);” should be “mysql_close($connection);”
    because the older function was depreciated from PHP 7.

    Reply
    1. blankNick Tate

      sorry that should be “mysqli_close($connection);”

      Reply
      1. blankRavi Bandakkanavar Post author

        Hi Nick,

        Thanks for pointing it out. Sorry about that.

        I corrected it. Take a look now.

        Since we are storing the database connection object in the variable $db, we should use the variable $db while closing a connection and it should be done at two places.
        1.Login.php
        2.Logout.php

        $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
        .
        .
        mysqli_close($db);

        Reply
  20. blankS ALOKA PATRO

    hello sir, i need to make a website with login page.which type of validation should be best for me ?i have tried js validation but at the background in the pagesource somebody might find my id and password.please help me sir.

    Reply
    1. blankRavi Bandakkanavar Post author

      Hi Aloka,

      Yes. Using javascript would expose your values. You can overcome this by using database validation.
      I have mentioned following chunk of code in Login.php.

      if ($_SERVER['REQUEST_METHOD'] == 'POST')
      {
      if (empty($_POST['username']) || empty($_POST['password'])) //This is the way to validate inputs using PHP code but here we are using javascript validations so it is not necessary
      {
      echo "Please enter the correct Username and Password";
      //header("location: LoginForm.php");//You will be sent to Login.php for re-login
      }

      The database validation would consume little more time as compared to JS validations but in the case of JS, it would increase the web page size. You need to choose based on your requirement.

      If you still want to go for Javascript validations, you can use document.getElementById() to read from fields and have the code at a separate place by giving a reference in the head.

      My suggestion to you: go for certain frameworks which will reduce a lot of your work. some famous ones are https://laravel.com/, https://cakephp.org/ etc.

      Keep us updated with what you choose and about your website and Good Luck :)

      Reply
  21. blankRavi Bandakkanavar Post author

    Updated the Login application with PHP 7.0 supported methods as many methods like mysql_real_escape_string(), mysql_query(), mysql_num_rows(), mysql_connect(), mysql_select_db(), mysql_close() were depricated in PHP 5 and removed from the latest version of PHP i.e. PHP 7.0.

    Reply
  22. blankK.Sangavi

    Hi Sir,
    How to run php in xamp. How to connect html and sql for online library renewal system for mini project.

    Reply
    1. blankRavi Bandakkanavar Post author

      Hi Sangavi,

      Please go through following post to understand on html or php files location and also to create SQL database.
      Xamp and wamp both are almost same.

      Reply
  23. blankDinesh

    can you give me an idea for my mini project so that it will be helpful for my career.

    Reply
  24. blankKiran

    Good post sir. Its easy to unserstand.
    Logic to find number of logged in users is nice.
    Thank you sir.

    Reply
      1. blankKhabib

        I just change my local server from Apache Triad 2 to XAMPP and PHP7. I was getting crazy because what I’ve been create dont work at all. Including a simple login page. Then I found this page and this is very helpfull. I very appreciate.

        Thank You very much mate. Keep on posting.

        Reply

Did it help? Comment here..