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 :