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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php //Define your host here. $HostName = "localhost"; //Define your database name here. $DatabaseName = "id2070055_reactnativedb"; //Define your database username here. $HostUser = "id2070055_reactnativedb_user"; //Define your database password here. $HostPass = "1234567890"; ?> |
Code for User_Login.php file :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
<?php // Importing DBConfig.php file. 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']; //Applying User Login query with email and password match. $Sql_Query = "select * from UserRegistrationTable where email = '$email' and password = '$password' "; // Executing SQL Query. $check = mysqli_fetch_array(mysqli_query($con,$Sql_Query)); if(isset($check)){ $SuccessLoginMsg = 'Data Matched'; // Converting the message into JSON format. $SuccessLoginJson = json_encode($SuccessLoginMsg); // Echo the message. echo $SuccessLoginJson ; } else{ // 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 the message. echo $InvalidMSGJSon ; } mysqli_close($con); ?> |
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.
1 2 3 4 5 6 |
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'; |
6. Create a new activity class named as LoginActivity.
1 2 3 4 |
class LoginActivity extends Component { } |
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.
1 2 3 4 5 6 7 8 |
class LoginActivity extends Component { // Setting up Login Activity title. static navigationOptions = { title: 'LoginActivity', }; } |
8. Creating constructor with props in class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class LoginActivity extends Component { // Setting up Login Activity title. static navigationOptions = { title: 'LoginActivity', }; constructor(props) { super(props) this.state = { UserEmail: '', UserPassword: '' } } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
UserLoginFunction = () =>{ const { UserEmail } = this.state ; const { UserPassword } = this.state ; fetch('https://reactnativecode.000webhostapp.com/User_Login.php', { 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 }); } else{ Alert.alert(responseJson); } }).catch((error) => { console.error(error); }); } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
render() { return ( <View style={styles.MainContainer}> <Text style= {styles.TextComponentStyle}>User Login Form</Text> <TextInput // Adding hint in Text Input using Place holder. placeholder="Enter User Email" onChangeText={UserEmail => this.setState({UserEmail})} // Making the Under line Transparent. underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput // Adding hint in Text Input using Place holder. placeholder="Enter User Password" onChangeText={UserPassword => this.setState({UserPassword})} // Making the Under line Transparent. underlineColorAndroid='transparent' style={styles.TextInputStyleClass} secureTextEntry={true} /> <Button title="Click Here To Login" onPress={this.UserLoginFunction} color="#2196F3" /> </View> ); } |
Screenshot of LoginActivity :
11. Now Add a New activity named as ProfileActivity in your project.
1 2 3 4 |
class ProfileActivity extends Component { } |
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.
1 2 3 4 5 6 7 8 9 10 11 |
class ProfileActivity extends Component { // Setting up profile activity title. static navigationOptions = { title: 'ProfileActivity', }; } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
class ProfileActivity extends Component { // Setting up profile activity title. static navigationOptions = { title: 'ProfileActivity', }; render() { const {goBack} = this.props.navigation; return( <View style = { styles.MainContainer }> <Text style = {styles.TextComponentStyle}> { this.props.navigation.state.params.Email } </Text> <Button title="Click here to Logout" onPress={ () => goBack(null) } /> </View> ); } } |
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.
1 2 3 4 5 6 7 |
export default MainProject = StackNavigator( { First: { screen: LoginActivity }, Second: { screen: ProfileActivity } }); |
15. Now add CSS styles :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
const styles = StyleSheet.create({ MainContainer :{ justifyContent: 'center', flex:1, 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 } }); |
16. Complete source code for App.js file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 |
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) { super(props) this.state = { UserEmail: '', UserPassword: '' } } UserLoginFunction = () =>{ const { UserEmail } = this.state ; const { UserPassword } = this.state ; fetch('https://reactnativecode.000webhostapp.com/User_Login.php', { 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 }); } else{ Alert.alert(responseJson); } }).catch((error) => { console.error(error); }); } render() { return ( <View style={styles.MainContainer}> <Text style= {styles.TextComponentStyle}>User Login Form</Text> <TextInput // Adding hint in Text Input using Place holder. placeholder="Enter User Email" onChangeText={UserEmail => this.setState({UserEmail})} // Making the Under line Transparent. underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput // Adding hint in Text Input using Place holder. placeholder="Enter User Password" onChangeText={UserPassword => this.setState({UserPassword})} // Making the Under line Transparent. underlineColorAndroid='transparent' style={styles.TextInputStyleClass} secureTextEntry={true} /> <Button title="Click Here To Login" onPress={this.UserLoginFunction} color="#2196F3" /> </View> ); } } // Creating Profile activity. class ProfileActivity extends Component { // Setting up profile activity title. static navigationOptions = { title: 'ProfileActivity', }; render() { const {goBack} = this.props.navigation; return( <View style = { styles.MainContainer }> <Text style = {styles.TextComponentStyle}> { this.props.navigation.state.params.Email } </Text> <Button title="Click here to Logout" onPress={ () => goBack(null) } /> </View> ); } } export default MainProject = StackNavigator( { First: { screen: LoginActivity }, Second: { screen: ProfileActivity } }); const styles = StyleSheet.create({ MainContainer :{ justifyContent: 'center', flex:1, 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 } }); |
Screenshot in Android Device :
Screenshot in iOS device :
i’ve no response when i click ‘login button’. whats wrong? help me please
Nabil please follow my registration tutorial to know how tables are created in this tutorial and then follow this tutorial.
okay I can handle it.
but how if I want to create login session using API? I want take the username and password from my API.
I’m so glad if you can help me Sir, thankyou 🙂
Login Season for what purpose ?
Login same as you ever made. but i want take the username and password from my API not from local db.
Nabil here API means online MySQL database ?
yes Sir. here’s my API https://dicbn.cbn.net.id/api/member/login
I want to get username and password from there
Nabir first you need to read my user registration tutorial : https://reactnativecode.com/react-native-user-registration-example-tutorial/ and follow all the steps which i have put in tutorial.
yes I’ve follow your tutorial before, thats working well when I using local db. But for online API, I confused where I can put my API link
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.
Thanks for comment Tony, I will soon publish a new tutorial regarding to your query 🙂 .
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?
May read my tutorial about CRUD operations in react native app using PHP MySQL : https://reactnativecode.com/insert-update-display-delete-crud-operations/ i have explained all the steps there 🙂 .
I’ve added it into my module. However, it is based on Listview to get the id of user when click on it. But, can you give any suggestion so that after login, the cuurent user id is stored and update the user profile when needed without listing all the users in the database.
Thank you
May please repeat your question more briefly with more information .
Hello,
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?
Thanks
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.
sir i did the same..but now it shows that “the development server returned response error code:500 ” and on the line export default const MainProject = StackNavigator() it shows syntax error.
Shivani send me your code on [email protected] 🙂 .
not working for like this.can you share me whole project zip
Gaurav, there is no need to download the whole project just follow all the steps and i have already put all the code in post 🙂 .
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
fetch(‘https://reactnativecode.000webhostapp.com/User_Login.php’
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 : https://pastebin.com/QhzSVu1r
Bro you are using the file config.php did you put your correct server username, database and all the info inside that file ?
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 ?
it is same as yours because when i out the url to your website it works but with mine no
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!
Sir, Mail has been sent. Check it out
Replied your mail 🙂 .
Yeah It’s Working now , Thank you sir for your prompt solution. 🙂
Welcome Shivani 🙂 .
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.
I’ve checked it, my database name and database user name, password is just right.
On which platform you are testing this app like online or local.
local sir
I try to use my ip address but didn’t work
fetch(‘http://192.168.***.***/onepiece/User_Login.php’
I’ve the same errors as you, it’s a syntax error of the formated json data that you send to php, and then your ‘ json_decode’ can’t really read it. Check if your both file are in UTF-8 maybe.
I’ve still this problem, i check other solutions…
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 ?
Tristan could you tell me on which platform you have testing this code line online or local ?
Hi, admin ! I have a very similar error with Tristan1075 :
“SyntaxError: Unexpected token { in JSON at position 47”.
I copied your code in my app, it’s the same. What’s wrong ? Can you help me ?
what if i want tab navigator after login?
Then navigate to Tab navigator activity.
Does this maintain State persistence?
No, why ?
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..
Yes JOY, you can do that but can you first explain me more briefly ?
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
Ratnesh you are using this to send the login email to next activity ?
Yes admin when i get success response from fetch method then as you have done i am doing the same but i am not able to get the email id on profile page
Hi admin,
Check your email please
any one managed to fix the JSON parse error: Unexpected Token ‘<'
Hassan there is no error in the code you should check the database config file.
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?
You can use the normal passing method which we would use between passing parameters read our this tutorial this would help you: https://reactnativecode.com/pass-textinput-entered-value-activity-screen/
Nice tutorial…
Btw, how to clear text input after clicking Login button?
Simply set =”” value in state which used as text input value.
hi, admin.
this is a great tutorial, your code’s works absolutely fine, but it goes error when I move to another activity.
scenario:
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.
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 !
Cesar you want to automatic logout after closing the app ? please explain your question more briefly ?
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
Francois you need to put your local system IP address instead of localhost like http://YourSystemIP/UserInfo/submit_user_info.php in URL .
I need you as a consultant in my project.How much do you charge..Can we talk?
Nipa there is no charge, you can ask your any query on my email [email protected] . If i will be able to solve it i will sure.
🙂 🙂
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.
Yes bro you can make query on another page read my this tutorial this would help you : https://reactnativecode.com/click-filter-json-selected-listview-data-android-ios/
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.
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 ?
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.
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?
yes kelly 🙂 .
uhmm, ok, thx
Welcome kelly 🙂 .
php
———————
react-native
———————-
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) {
super(props)
this.state = {
UserEmail: ”,
UserPassword: ”,
UserId:this.props.navigation.getParam(‘user_id’),
}
}
UserLoginFunction = () =>{
const { UserEmail } = this.state ;
const { UserPassword } = this.state ;
const { UserId } = this.state;
fetch(‘http://192.168.92.1/login/login.php’, {
method: ‘POST’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
email: UserEmail,
password: UserPassword,
user_id:UserId,
})
}).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 });
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
render() {
return (
User Login Form
this.setState({UserEmail})}
// Making the Under line Transparent.
underlineColorAndroid=’transparent’
style={styles.TextInputStyleClass}
/>
this.setState({UserPassword})}
// Making the Under line Transparent.
underlineColorAndroid=’transparent’
style={styles.TextInputStyleClass}
secureTextEntry={true}
/>
);
}
}
// Creating Profile activity.
class ProfileActivity extends Component
{
// Setting up profile activity title.
static navigationOptions =
{
title: ‘ProfileActivity’,
};
render()
{
const {goBack} = this.props.navigation;
return(
{ this.props.navigation.state.params.email }
{this.props.navigation.state.params.user_id}
goBack(null) } />
);
}
}
export default MainProject = StackNavigator(
{
First: { screen: LoginActivity },
Second: { screen: ProfileActivity }
});
const styles = StyleSheet.create({
MainContainer :{
justifyContent: ‘center’,
flex:1,
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
Thanks for comment but i am out of station and my laptop is not with me so sorry currently i cannot modify you code .
php file is here
————————-
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));
if(isset($check)){
$SuccessLoginMsg = ‘Data Matched’;
// Converting the message into JSON format.
$SuccessLoginJson = json_encode($SuccessLoginMsg);
// Echo the message.
echo $SuccessLoginJson.$ID ;
}
else{
// 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 ;
}
mysqli_close($con);
its ok admin, but can u modify as long as you come back? Because I really need your help, thank you
Sure kelly 🙂 .
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 .
In react native how to extract it, response[0].id or this.props.navigation.get.id?
response[0] should get you the fist value of array .
I will try again, thanks admin
Hey admin, I finally get the user_id, thank you
Welcome kelly and thanks for becoming part of my website 🙂 .
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.
Vivek the code of config.php is not here in comment , please post the code of your file .
hy bro .
It will be highly appreciated if you upload tutorials on touch-id authentication or identification and then store data on mysql
Adubakar please can you explain here touch id mean ?
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
Thanks for explaining about touch id. I will look into it .
I am facing following error
JSON Parse error: Unrecognized token ‘<'
Pratik put your own server database name, database username, database password and host name in database config file.
and i am looking forword to watch example tutorial on this topic
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.
First of all thanks Rizwan and sure i will make a explanation tutorial for you 🙂 .
Thank you very very much
that was perfect
Thanks 🙂 .
how can i find the url on fetch when i use a local server ??
The fetch URL is your IpAddress/Filename.php .
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.
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?
Thanks for notifying us Drtyrell. I will remove the App Registry from the code.
I get the error : JSON Parse error: Unexpected EOF. Why could that be?
Isac you are what changes your are making in my project ?
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) {
super(props)
this.state = {
username: ”,
password: ”,
}
}
UserLoginFunction = () => {
const { username } = this.state;
const { password } = this.state;
fetch(‘http://192.168.64.3/user_login.php’, {
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.
this.props.navigation.navigate(‘Home’);
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
And of course the render of the TextInputs and button which calls UserLoginFuction onPress.
Also my user registration works perfectly with the help of your other tutorial.
Isac you are testing this code on local server or online ?
I now tried to create a new project from scratch and copied your entire code and still get the same error message…
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.
im testing on a local server
Isac the you need to put your local system iP address and then the folder and file path . Read my this tutorial this would help you : https://reactnativecode.com/connect-run-apps-using-localhost/
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
Farah did you change the login file URL also same as registration and also read my this tutorial this would help you : https://reactnativecode.com/connect-run-apps-using-localhost/ .
Thankyou! I’ve just realized that I use https rather than http and I’ve already fixed it
Thanks for notifying us 🙂 .
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.
Hello sir.
Now, I’m facing an error saying
(0,_reactNavigation.StackNavigator)is not a function.(In'(0,_reactNavigation.StackNavigator)({
First:{
screen: LoginActivity},
Second: { screen: ProfileActivity }
})’,'(0,_reactNavigation.StackNavigator)’ is undefined)
could you help me to solve this?
Thank you sir.
Neeranet the stack navigator is deprecated in latest version of react navigation you have to use createStackNavigator. Read my this tutorial this would help you : https://reactnativecode.com/getting-started-with-react-navigation/ .
Wow thankyou for your explanation!
Welcome Farah 🙂 .
i’m so greatful for this wonderful tut
thanks alot , you have reduce many stress in my life
Thank you very much admin. 🙂
Welcome Neeranet 🙂 .
I replaced the stacknavigator with createstacknavigator calls and the code is as given below:
But i dont find the code working.i get only “no bundle url present” error.
The code is as follows:
import React, { Component } from ‘react’;
import { AppRegistry, StyleSheet, TextInput, View, Alert, Button, Text } from ‘react-native’;
//import Loginform from ‘./Loginform’;
/*import RegisterForm from ‘./RegisterForm’;
class App extends Component {
render() {
return ;
}
}
export default App;*/
// Importing Stack Navigator library to add multiple activities.
import { createStackNavigator, createAppContainer } from ‘react-navigation’;
// Creating Login Activity.
class LoginActivity extends Component {
// Setting up Login Activity title.
static navigationOptions =
{
title: ‘LoginActivity’,
};
constructor(props) {
super(props)
this.state = {
UserEmail: ”,
UserPassword: ”
}
}
UserLoginFunction = () =>{
const { UserEmail } = this.state ;
const { UserPassword } = this.state ;
fetch(‘https://reactnativecode.000webhostapp.com/User_Login.php’, {
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 });
}
else{
Alert.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
render() {
return (
User Login Form
this.setState({UserEmail})}
// Making the Under line Transparent.
underlineColorAndroid=’transparent’
style={styles.TextInputStyleClass}
/>
this.setState({UserPassword})}
// Making the Under line Transparent.
underlineColorAndroid=’transparent’
style={styles.TextInputStyleClass}
secureTextEntry={true}
/>
);
}
}
// Creating Profile activity.
class ProfileActivity extends Component
{
// Setting up profile activity title.
static navigationOptions =
{
title: ‘ProfileActivity’,
};
render()
{
const {goBack} = this.props.navigation;
return(
{ this.props.navigation.state.params.Email }
goBack(null) } />
);
}
}
const RootStack = createStackNavigator(
{
Home: LoginActivity,
Second: ProfileActivity
},
{
initialRouteName: “Home”
}
);
const AppContainer = createAppContainer(RootStack);
export default AppContainer;
const styles = StyleSheet.create({
MainContainer :{
justifyContent: ‘center’,
flex:1,
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
}
});
I cant able to navigate to ProfileActivityPage after entering the email and password which already has in the database. Admin please help.
Supriya, what error is coming ? Could you please tell me ?
though i am giving correct data for log in but every time same alert pops up ‘Invalid Username or Password Please Try Again’
Hello,
Is there anyway to do this tutorial without PHP..?
I am trying to make a login screen using React-Native and SQL database.
And it would be really helpful if you could update the article since it is outdated.
React-native updated a lot so some of the code doesn’t work.
Sure Pasan i will post new tutorial with updated code within 3 days form now.
Hi my friend,
did you already made a new tutorial for a MySQL User Login,
because this one is not working anymore?
There’s no response coming from
$json = file_get_contents(‘php://input’);
Thank you
Aahana 🙏🏾
Thanks for notifying us Aahana i will make a new tutorial regarding same topic soon 🙂 .
Thank you so much! I’m really stucked here.
Everything of your tutorial works perfekt, but i cannot transfer the text from the inputfield to the php file.
Aahana did you change the PHP file configuration from your server configuration ?
demo of login with node js and mongodb
Hi Admin, i have tried to insert data in the db manually, but when i try to login in, i get Network request failed error
i’m running it on the local machine inside Xamp/htdocs/react_projects/mobile @https://machineIP/react_projects/mobile/User_Login.php
When I seem to run my code, I am able to enter a username and password and I given the response data match but I don’t seem to be taken to the profile screen, any reason for this as my code is the same as above.
Rebekah because this tutorial is with old Stack Navigator and now the Stack navigator is deprecated you should use createstacknavigator.
I should have stated that I have actually been using createstacknavigator and have come across this problem.
The login is great, but I would like to know how to make the login identify the user, that is a type of user, my table is the same only has added type of user. It is so that when the user uses the login, they send it to a different screen by type of user
my query is
$Sql_Query = “select tipo_usuario from usuarios where user = ‘$user’ and password = ‘$password’ “;
How can User login, automatically login, when logged in once a user logs in?
Network request failed error
please help me to slove this
Hi Admin, its really a nice tutorial. I have slightly modified it. Instead of
php I have used nodejs and its working fine.
Thanks a ton.
Welcome Ajay 🙂 .
Hi! Thats awesome!
Can you do it with token also? How our app can understand if the user is already signed in?
Thank you 🙂
You can AsyncStorage to store a token value in app local memory on each time when user successfully logged in and if the user dose not click on the sign out button and close the app then it will check the token is present on memory on app start time and if the toke is present then it will automatically sign in the user.
Hello,
I would like to display the id and name of the logged in user instead of the email address. How can I do ?
hello how i can login with facebook or google button?
Anis read my this tutorial this would help you : https://reactnativecode.com/facebook-login-integration/ .
Hi Admin. Thanks for your example. i am grateful.
My question is ;
after login , How can i create tab bar bottom menu ? Can you show me a way on this subject?
Thanks again.
Yatil simply write the Tab bar bottom menu code in Profile file.
Yes , i did that too. But i have a new problem.
for example , i created tab bar bottom menu. into profil screen i want to click ‘seetings’ button. and please look my code :
<Button
buttonStyle={{
backgroundColor:'#f06400',
elevation: 8,
borderRadius: 10,
paddingVertical: 10,
paddingHorizontal: 12,
}}
icon={
}
title=”Ayarlar”
onPress={()=>navigation.navigate(‘Settings’)}
/>
Why onPress is not working? Error is : ‘seetings’ not found. But I made the definition in AuthStack.js . And i create SettingsStack.js and SettingsScreen.js.
Thank your answer.
what should i used instead of “data match when i have no “data match ” word in my php my file
Sohil there is always a keyword on successfully data transmit, You can define that keyword in the PHP file.
im getting this type of erro :
function() { return this.next().then(JSON.-parse);
instead of data
Sohil you are getting the success message as “Success”, can you share your code ?
API Link – https://nasdigital.tech/Android_API_CI/validate_login_details
request JSON – [{“username”:”[email protected]”,”password”:”nasdigital123″}]
response JSON – {“message”:”success”,”data”:[{“first_name”:”Nasdigital”,”last_name”:”Admin”,”email_id”:”[email protected]”}]}
i want this response when i login with that username nd password please help me
thanks for the tutorial sir, but I have a problem when I run the program why does “Network Request Failed” appear, how can I solve it, sir? Please help
Andriani can you tell me on which platform you are testing the app ?
Hi, Sir
This is a great tutorial, your code’s works absolutely fine, but it goes error when I move to another
error:
undefined is not an object (evaluating ‘this.props.navigation.state.params.Phone’)
Please help
Hello, thank you for the tutorial, but i get this error when i run on my samsung device: TypeError: (0, _$$_REQUIRE(_dependencyMap[9], “react-navigation”).StackNavigator) is not a function.
Adekunle Adeyeye this is showing this message because the React Navigation, I am using in this tutorial is upgraded so you have to use their new functions.
Hello, Nice tutorial, I tried it but the form seems not to be sending any data to the PHP file, what could be the cause of that?
Neka you are trying this code on locally or online please tell me ?
How can we create session in react native
Shubham, You can create season in react native but you have to use local database or online database to store the season value .
Hi thanks for this tutorial, I have question, react native using mySql is no need for session login?
No Rey you can manage season without mySQL.