React Native User Login Using PHP MySQL Android iOS Example Tutorial

As we have discussed in our previous tutorial about User Registration with PHP MySQL. This tutorial is the second part of that tutorial in this tutorial we would going to create a react native application that gives us the functionality to Login the already registered user and after successfully login it will redirect us to Profile page. So let’s get started 🙂 .

What we are doing in this project ( Project Description ) :

In this project we are going to create a react native application with 2 Activities. First is LoginActivity, which shows us the user Login form containing 2 Text Input and 1 Button component. Now when user clicks on the Login button then we start a web call on server using fetch method, which send the User Email and Password on server. Now we would receive the email and password on server using PHP script, after that we would match the Email and Password using SQL command and on success of that match we will print a response message using Echo. Now we would receive that response in our react native application.

After receiving that response if the response == Data Matched then we would open a new activity named as Profile activity and send the user email to Profile activity. If you have any query regarding this tutorial feel free to comment 🙂 .

Database used in this tutorial : MySQL

Server Side scripting Language used in this tutorial : PHP

Contents in this project User Login Using PHP MySQL tutorial :

1. Read my previous tutorial User Registration with PHP MySQL . I have explained all about creating MySQL database in that tutorial.

2. Create PHP Script to Match received Email and Password from App into MySQL database and send response to application :

Create 2 PHP files DBConfig.php and User_Login.php .

DBConfig.php : This file contains the MySQL database hostname, database name, database password and database username.

User_Login.php : This file would receive the user email and password and match them into MySQL database using SQL command.

Code for DBConfig.php file :

Code for User_Login.php file :

3. Start a fresh React Native project. If you don’t know how then read my this tutorial.

4. We are using 2 Activities in our project, First one is LoginActivity and Second is ProfileActivity. So read my this tutorial to learn about Adding Activities in our react native project.

5. Now add AppRegistry, StyleSheet, TextInput, View, Alert, Button and Text component in import block.

Add stack Navigator import line.

6. Create a new activity class named as LoginActivity.

7. Add static navigation options inside LoginActivity. Using the static navigationOptions we can set the activity title name which displays inside the Action bar / Title bar.

8. Creating constructor with props in class.

9. Create UserLoginFunction() in LoginActivity .

In this function we would first get the Email and Password from Text Input using state. Now we would send that email password to server and receive them using PHP script we have created earlier in this project.

10. Add render’s return block in your LoginActivity and inside that First set a parent View, Inside that parent view place 2 TextInput and 1 Button component. Calling the LoginFunction on button onPress.

Screenshot of LoginActivity :

11. Now Add a New activity named as ProfileActivity in your project.

12. Add static navigation options inside ProfileActivity . Using the static navigationOptions we can set the activity title name which displays inside the Action bar / Title bar.

13. Create render’s return block in ProfileActivity. Now create const {goBack} = this.props.navigation method inside the render block. This will help us to enable activity closing using button click. Add a View as parent and inside that View add 1 Text and 1 Button component.

Text component : is used to show the user email entered by user at login time on LoginActivity.

Button : is used to Logout from Profile Activity and after that it will automatically redirect to Login Activity.

Screenshot of Profile Activity :

14. Navigate the LoginActivity and ProfileActivity using StackNavigator method. Place this code just after the ProfileActivity class.

First object navigate to LoginActivity.

Second object navigate to ProfileActivity.

15. Now add CSS styles :

16. Complete source code for App.js file.

Screenshot in Android Device :


Screenshot in iOS device :


  1. i’ve no response when i click ‘login button’. whats wrong? help me please

  2. yes Sir. here’s my API
    I want to get username and password from there

  3. Hello Sir, may i request tutorial about API backhandler? i will implement it for this login tutorial, so when i press hardware back button on ProfileActivity not direct navigate to LoginActivity, but call a function.

  4. Hello Sir, I try to add new function to update my account after login by clicking on update button in profileactivity page. What steps should be taken in php file? How to get the same ID after login and when update the profile?

  5. Online Franz Tech

    Thanks for the simple tutorial but i have a problem, i did exactly as you, copy & paste but i have a error saying ” JSON Parse Unexpected Token ‘<' ". but when i use your 000webhost link, it works What is wrong?

    • Bro i have just run the code and it is running absolutely fine, you need to add export default at the starting of class like export default class LoginActivity extends Component { and remove the AppRegistry.registerComponent(‘MainProject’, () => MainProject); from the code.

      • hello sir, when i add export default at the starting of class like export default class LoginActivity extends Component { and remove the AppRegistry.registerComponent(‘MainProject’, () => MainProject); from the code. it shows error that ” undefined is not an object(evaluating ‘this.props.navigation.navigate’)” why it is showing this?

        • Shivani you need to add export default at the starting of const MainProject = StackNavigator() like export default const MainProject = StackNavigator() and remove the export default from class LoginActivity.

      • Online Franz Tech

        Hello Sir, I’ve done it but it is not still working. I have the same react native and PHP code as you. When I set

        it works but with mine not though I have the same code as you.
        Please help me.

        The react native code is the same
        here is my php code :

        • Bro you are using the file config.php did you put your correct server username, database and all the info inside that file ?

          • Online Franz Tech

            Yes Sir, if not it wouldn’t work on the website URL directly.
            I try, it was working on my browser but in React Native not.

          • Your PHP code is looks fine to me what about your react native code ?

          • Online Franz Tech

            it is same as yours because when i out the url to your website it works but with mine no

        • Online Franz Tech

          I Was having this pb too but now anymore.

          This problem is caused due to different reasons
          It took me 45 days to find these solutions

          1. MANAUAL ERROR : check you ain’t returning a html code by doing: echo “g”; for example
          2. SERVER ERROR :
          if you notice, when you use Sardar’s URL, it works and with yours maybe it doesn’t. This means that the error is from the server and not from React Native.
          Sardar uses 000webhost, I was using AwardSpace free plan: After creating a 000webhost account,
          I discovered that 000webhosting has PHP 7 default and mine was PHP 5 so i suggested that the server was returning an error somewhere so i simply changed the PHP version of my server to PHP 7!

          Shortly : try to change your server php version to PHP 7+!

          Hope this will helped you!

  6. Sir, Mail has been sent. Check it out

  7. will this still work if i didn’t make a registration form?

    • Then you need to manually enter the registration details first into the MySQL database.

      • yeah, i’m done doing that.
        Now, i’m facing an error saying;
        JSON parse error unrecognized token ‘<'.
        Even though I follow everything in your tutorial.

        • and sometimes it gives me;
          Module HMRClient is not registered callable modlue (calling enable)
          what does it mean, sir?

          • Ok, I manage to fix the;
            Module HMRClient is not registered callable modlue (calling enable) error, the only remaining one is the;
            JSON Parse error: Unrecognized token ‘<'.

          • check your database config file for your server configuration is correct like database name and database user name, password.

  8. I’ve checked it, my database name and database user name, password is just right.

  9. Hello, i’m having a Syntax error when i fetch my API
    ” SyntaxError: Unexpected token N in JSON at position 1 stringify”.

    I tought it came from my react app but it quit same as yours.. Do you have an idea ?

  10. what if i want tab navigator after login?

  11. Does this maintain State persistence?

  12. Hello Sir,
    Thank you so much Sir for this very useful tutorial… I would want sir to use a web service to be able to call a function from our existing web app… would that be possible sir? we have an LDAP authentication and MS SQL as backend..

  13. Hello admin i am getting this error “undefined is not an object (evaluating ‘this.props.navigation.state.params’)” when i am using “this.props.navigation.state.params.Email” in my code on login activity. i am using StackNavigator inside DrawerNavigator Like this
    export default MyDrawerNavigator = DrawerNavigator({
    Home: {
    screen: FirstActivity_StackNavigator

    Login: {
    screen: SecondActivity_StackNavigator

    Register: {
    screen: ThirdActivity_StackNavigator
    Profile: {
    screen: FourthActivity_StackNavigator

    when I enter my credential into login form and it will be successfull then i see this problem

  14. any one managed to fix the JSON parse error: Unexpected Token ‘<'

  15. Hello Admin. Do you know how to pass parameters between a StackNavigator and a DrawerNavigator?

    In the app I’m making, after login it will move to profile screen which is in a DrawerNavigator. However I can’t seem to pass the email from login to profile page. Any ideas?

  16. Nice tutorial…
    Btw, how to clear text input after clicking Login button?

  17. hi, admin.

    this is a great tutorial, your code’s works absolutely fine, but it goes error when I move to another activity.

    login -> profile (works fine)
    profile -> to another activity (TypeError: underfined is not an object (evaluating ‘this.props.navigation.state.params.Email’)

    please help.

    • Jemmy you should use this.props.navigation.navigate(‘Second’) ; or this.props.navigation.navigate(‘Third’); to goto another activity from profile . here the Third is the object used to access the activity as second.

  18. i love your tutorials!
    i been follow this same tutorial but i’m wondering how can persist the login when the app close down
    i read that it’s with asyncStorage but i don’t know how to do it 🙁
    could you please help me?
    i’ll be very greatfull 🙂
    regards !

  19. Hello Sir,
    Thanks for the tutorial! 🙂
    I get the following error:
    ‘JSON Parse error: Unrecognized token ‘<''

    I put http://localhost/UserInfo/submit_user_info.php in my browser and get 'try again'
    No errors relating to login…

    What should I do?? I've been stuck on this for 2 days now

    Thanks in advance

  20. I need you as a consultant in my project.How much do you charge..Can we talk?

  21. Hello sir, your tutorial is good and your code working well, i want question to you, if I want to retrieve data from the database from the login session data, so I can display the name based on the query that I created on a different page. that’s how I can solve it sir? can you help me ? Thanks.

  22. Is there any tutorials on sign up page?

    • No, I haven’t make a tutorial on Sign up because i am learning the email verification now after that i will sure post tutorial on it.

  23. Hello bro, please I would like to open profile activities on a different screen how can I do that.

    • Different screen means you want to first login then want to goto another screen then from there want to open profile screen, am i right ?

  24. Hello, may I know how to display the user id after I login

    • Kelly after successfully login simply send the user id with login successfully message and receive the ID into application.

      • u mean send the user id in php file? I am sorry but can you please elaborate more clearly?

        • Kelly when we try to login from certain user name and password then after login all you have to do it transfer the login user id or email from PHP file to react native app with response message.

  25. is it like this? first after the $password=$obj[‘password’] I add a $user_id=$obj[‘user_id’];
    And then in successful msg pass the value like this $SuccessLoginMsg = ‘Data Matched’+$user_id; is it like this?

  26. uhmm, ok, thx

    • Welcome kelly 🙂 .

      • php


        import React, { Component } from ‘react’;

        import { StyleSheet, TextInput, View, Alert, Button, Text} from ‘react-native’;

        // Importing Stack Navigator library to add multiple activities.
        import { StackNavigator } from ‘react-navigation’;

        // Creating Login Activity.
        class LoginActivity extends Component {

        // Setting up Login Activity title.
        static navigationOptions =
        title: ‘LoginActivity’,

        constructor(props) {


        this.state = {

        UserEmail: ”,
        UserPassword: ”,


        UserLoginFunction = () =>{

        const { UserEmail } = this.state ;
        const { UserPassword } = this.state ;
        const { UserId } = this.state;

        fetch(‘’, {
        method: ‘POST’,
        headers: {
        ‘Accept’: ‘application/json’,
        ‘Content-Type’: ‘application/json’,
        body: JSON.stringify({

        email: UserEmail,

        password: UserPassword,



        }).then((response) => response.json())
        .then((responseJson) => {

        // If server response message same as Data Matched
        if(responseJson === ‘Data Matched’)

        //Then open Profile activity and send user email to profile activity.
        this.props.navigation.navigate(‘Second’, { email:UserEmail, user_id:UserId, password:UserPassword });



        }).catch((error) => {


        render() {
        return (

        User Login Form


        // Making the Under line Transparent.



        // Making the Under line Transparent.




        // Creating Profile activity.
        class ProfileActivity extends Component

        // Setting up profile activity title.
        static navigationOptions =
        title: ‘ProfileActivity’,



        const {goBack} = this.props.navigation;


        { }


        goBack(null) } />


        export default MainProject = StackNavigator(
        First: { screen: LoginActivity },

        Second: { screen: ProfileActivity }


        const styles = StyleSheet.create({

        MainContainer :{

        justifyContent: ‘center’,
        margin: 10,

        TextInputStyleClass: {

        textAlign: ‘center’,
        marginBottom: 7,
        height: 40,
        borderWidth: 1,
        // Set border Hex Color Code Here.
        borderColor: ‘#2196F3’,

        // Set border Radius.
        borderRadius: 5 ,


        TextComponentStyle: {
        fontSize: 20,
        color: “#000”,
        textAlign: ‘center’,
        marginBottom: 15

        Admin, I am so sorry because I still cannot get the user id, can you please modify my code and tell me actually how to get it, thanks

  27. php file is here

  28. include ‘DBConfig.php’;

    // Creating connection.
    $con = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);

    // Getting the received JSON into $json variable.
    $json = file_get_contents(‘php://input’);

    // decoding the received JSON and store into $obj variable.
    $obj = json_decode($json,true);

    // Populate User email from JSON $obj array and store into $email.
    $email = $obj[’email’];

    // Populate Password from JSON $obj array and store into $password.
    $password = $obj[‘password’];

    $ID = $obj[‘user_id’];

    //Applying User Login query with email and password match.
    $Sql_Query = “select * from user where email = ‘$email’ and password = ‘$password'”;

    // Executing SQL Query.
    $check = mysqli_fetch_array(mysqli_query($con,$Sql_Query));


    $SuccessLoginMsg = ‘Data Matched’;

    // Converting the message into JSON format.
    $SuccessLoginJson = json_encode($SuccessLoginMsg);

    // Echo the message.
    echo $SuccessLoginJson.$ID ;



    // If the record inserted successfully then show the message.
    $InvalidMSG = ‘Invalid Username or Password Please Try Again’ ;

    // Converting the message into JSON format.
    $InvalidMSGJSon = json_encode($InvalidMSG);

    echo $InvalidMSGJSon ;



  29. its ok admin, but can u modify as long as you come back? Because I really need your help, thank you

  30. admin, I can output user_id in php, do you know how to make react native call the user_id which I get in php?

    • Kelly sorry for late reply, Please can you explain me your complete requirement like what you want from PHP file .

      • Yes admin, I am sorry for keep disturbing but I really need your help. In your example is pass the user key in email to the after login page is it. But what I want to try is to pass the email and user_id to the after login page

        • Kelly in my example when user successfully enter the right user name and password then we have send a response message Data Matched from server to our react native app and inside the app if the response is matched then we will navigate to next activity and if you want to send the user key or email id after successfully login then you have to send them together with response message like : $SuccessLoginMsg = array(“Data Matched”, $email, $ID); .
          Now it will send the email and id the react native app and from the app you can easily extract the data from json array .

  31. I will try again, thanks admin

  32. Now, i’m facing an error saying,
    JSON parse error unrecognized token ‘<'.
    I'm checking to online server but above error is coming.
    below my config.php file code available so let me know.

  33. hy bro .
    It will be highly appreciated if you upload tutorials on touch-id authentication or identification and then store data on mysql

  34. basically i want to build employee attendance system through fingerprint scan .
    react-native-touch-id is library which help to use fingerprint scanner of your cell phone

  35. I am facing following error

    JSON Parse error: Unrecognized token ‘<'

  36. and i am looking forword to watch example tutorial on this topic

  37. Dear Admin, bundle of thanks for such perfect tutorials.
    I am php developer, but quite new for React Native.
    I checked all your tutorials, code is very good understandable, but bit confused about how to make files/folders structure, because you are saving all codes in ” App.JS”. Can you please share any simple and good solution, in which folder we can put login activity file, in which folder we can put save data activity file and other files etc…. i checked with google, they are suggesting lot of frameworks which makes confusion. I need simple structure like for beginners.

  38. hassanbazarjani

    Thank you very very much
    that was perfect

  39. how can i find the url on fetch when i use a local server ??

  40. Hi, The code run absolutely correct but I want some modification like one you login and display screen profile if we refresh, It again ask for login(starting point). I want same screen(profile screen) from where it it reload.

    • Rashmi you want to ask for login each time when we logout or refresh the app, then you need to use the AsyncStroage in your project. Now save a value in Asyncstorage when user login and if user exit from app or refresh then set its value to false each time using componentwillunmount(). On each login time also check the value.

  41. You say to add “AppRegistry” to the import line, but it never shows up in your code. I’m running this on my Android phone. Is there something I need to do my my standard index.js?

  42. I get the error : JSON Parse error: Unexpected EOF. Why could that be?

  43. It’s very similar. My navigation code between screens work as intended without the UserLoginFunction(). My user_login.php is identical to yours. My SignIn class looks like this:

    class SignIn extends React.Component {
    constructor(props) {


    this.state = {
    username: ”,
    password: ”,

    UserLoginFunction = () => {
    const { username } = this.state;
    const { password } = this.state;
    fetch(‘’, {
    method: ‘POST’,
    headers: {
    ‘Accept’: ‘application/json’,
    ‘Content-Type’: ‘application/json’,
    body: JSON.stringify({

    username: username,

    password: password,


    }).then((response) => response.json())
    .then((responseJson) => {

    // If server response message same as Data Matched
    if(responseJson === ‘Data Matched’)

    //Then open Profile activity and send user email to profile activity.



    }).catch((error) => {


    And of course the render of the TextInputs and button which calls UserLoginFuction onPress.

  44. Also my user registration works perfectly with the help of your other tutorial.

  45. I now tried to create a new project from scratch and copied your entire code and still get the same error message…

  46. Hi! Thankyou for making this easy and simple tutorial. I’ve been following the tutorial from the user registration using local host and it works, so in this user login tutorial i use the localhost again (from your code, I only change the url in fetch function). However, when I try to login I get an error like this:

    Network request failed
    – node_modules\react-native\Libraries\vendor\core\whatwg-fetch.js:504:29 in onerror
    – node_modules\event-target-shim\lib\event-target.js:172:43 in dispatchEvent
    – node_modules\react-native\Libraries\Network\XMLHttpRequest.js:578:29 in setReadyState
    – node_modules\react-native\Libraries\Network\XMLHttpRequest.js:392:25 in __didCompleteResponse
    – node_modules\react-native\Libraries\vendor\emitter\EventEmitter.js:191:12 in emit
    – node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:349:47 in __callFunction
    – node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106:26 in
    – node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:297:10 in __guard
    – node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:105:17 in callFunctionReturnFlushedQueue
    * [native code]:null in callFunctionReturnFlushedQueue

    could you help me to solve this? I’m new to react-native and need this in my thesis. Thankyou!

    • Farah did you start the Xampp server and also your computer should connect to the internet while testing the code.

  47. im testing on a local server

  48. I’ve already start the Xampp server and my computer connect the internet too. It’s fine when I used the registration script but not with this login script

  49. Thankyou! I’ve just realized that I use https rather than http and I’ve already fixed it

  50. By the way, could you help me in this case: for example there are 3 category of users: student, teacher, and admin. In login screen they only need to enter user_id and password, then when navigate to the second screen is based on their users’ category (if it was student email then go to student screens). And the detail of these users are saved in different table (student in student_table, teacher in teacher_table, and admin in admin_table). What should I change in the PHP file and in app.js?

    • Farah you just want to give each user a specific page with specific permissions. To do so you can manage this in single table there is no need to use multiple tables just put a column in your table name as user_role. Now each time when user logins their data will come from sever and you have to make 3 screens for each user role so after login just check the user role and using the if condition or switch case simply navigate the user to his own page.

  51. Hello sir.
    Now, I’m facing an error saying
    (0,_reactNavigation.StackNavigator)is not a function.(In'(0,_reactNavigation.StackNavigator)({
    screen: LoginActivity},
    Second: { screen: ProfileActivity }
    })’,'(0,_reactNavigation.StackNavigator)’ is undefined)

    could you help me to solve this?
    Thank you sir.

  52. Wow thankyou for your explanation!

  53. Thank you very much admin. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *