React Native’s Fetch API is the most common and default Networking API used to send data from react native application to online server side MySQL database using PHP. Fetch API is mostly similar as XMLHttpRequest API. The Fetch API provides a JavaScript interface for accessing and transferring different parts of data using a secure HTTP pipeline. So in this tutorial we would going to create a react native app along with Networking Fetch API Tutorial to Insert Into MySQL Database Using PHP iOS Android Example. So let’s get started .
What we are doing in this tutorial :
We are simply inserting data from react native iOS and Android app to our online server side MySQL database using PHP.
- Database Used in this tutorial : MySQL
- Server Side Scripting Language : PHP
- API used in APP : Fetch Networking API
Contents in this project React Native Fetch API Tutorial to Insert Into MySQL Database Using PHP:
1. Create a MySQL Database and Table on your server .
Make New MySQL database or use your existing one. Create a Table inside MySQL database named as Products_Table along with 4 columns product_id, product_name, product_number and product_details. We would make the product_id as primary key with Auto Increment. See the below screenshot for more details.
Screenshot of Table after creating :
2. Create Server side code using PHP to receive data from App and Insert into MySQL database table :
We have to create 2 individual files to perform this functionality First is DBConfig.php and Second is Insert_Product.php .
DBConfig.php : This file contain all the important information about your MySQL server like Server Host name, server password, server user name and database name.
Insert_Product.php : This file would receive the sent data from Fetch API and insert that data into MySQL database.
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 Insert_Product.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
|
<?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 product name from JSON $obj array and store into $product_name.
$product_name = $obj[‘product_name’];
// Populate product number from JSON $obj array and store into $product_number.
$product_number = $obj[‘product_number’];
// Populate product details from JSON $obj array and store into $product_details.
$product_details = $obj[‘product_details’];
// Creating SQL query and insert the record into MySQL database table.
$Sql_Query = “insert into Products_Table (product_name,product_number,product_details) values (‘$product_name’,’$product_number’,’$product_details’)”;
if(mysqli_query($con,$Sql_Query)){
// If the record inserted successfully then show the message as response.
$MSG = ‘Product Successfully Inserted into MySQL Database’ ;
// Converting the message into JSON format.
$json = json_encode($MSG);
// Echo the message on screen.
// We would also show this message on our app.
echo $json ;
}
else{
echo ‘Something Went Wrong’;
}
mysqli_close($con);
?>
|
3. Import StyleSheet, View, TextInput, Text, ActivityIndicator and TouchableOpacity component in your react native project.
1
2
3
|
import React, { Component } from ‘react’;
import { StyleSheet, View, TextInput, Text, ActivityIndicator, TouchableOpacity } from ‘react-native’;
|
4. Create constructor() in your project’s class and make 4 States inside it named as Product_Name, Product_Number, Product_Details and ActivityIndicator_Loading.
Product_Name : Holds the Product name entered inside Product name TextInput.
Product_Number : Holds the Product Number entered inside Product Number TextInput.
Product_Details : Holds the Product Details entered inside Product Details TextInput.
ActivityIndicator_Loading : Used to show and hide the Activity Indicator .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
constructor()
{
super();
this.state = {
Product_Name: ”,
Product_Number: ”,
Product_Details: ”,
ActivityIndicator_Loading: false,
}
}
|
5. Create a function named as Insert_Data_Into_MySQL(). Inside this function we would create create the Fetch Networking API code to send the data from App to MySQL database. We would fist set the ActivityIndicator_Loading as true to show the ActivityIndicator on middle of screen while sending data.
- Method Used to send data using Fetch API is POST.
- headers : Tells the server that the Data is in JSON Object form.
- body : Contain all the Data with a unique identifier.
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
|
Insert_Data_Into_MySQL = () =>
{
this.setState({ ActivityIndicator_Loading : true }, () =>
{
fetch(‘https://reactnativecode.000webhostapp.com/Insert_Product.php’,
{
method: ‘POST’,
headers:
{
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify(
{
product_name : this.state.Product_Name,
product_number : this.state.Product_Number,
product_details : this.state.Product_Details
})
}).then((response) => response.json()).then((responseJsonFromServer) =>
{
alert(responseJsonFromServer);
this.setState({ ActivityIndicator_Loading : false });
}).catch((error) =>
{
console.error(error);
this.setState({ ActivityIndicator_Loading : false});
});
});
}
|
6. Create a Root View in render’s return block. This View would hold all the TextInput and TouchableOpacity component.
1
2
3
4
5
6
7
8
9
10
11
|
render()
{
return(
<View style = { styles.MainContainer }>
</View>
);
}
|
7. Create 3 TextInput component inside the Root View.
placeholder : Is used to show hint inside the Text Input.
style : Is used to call the custom CSS style class.
underlineColorAndroid : Hide the TextInput’s own underline.
onChangeText : Store the TextInput inside typed text into State.
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
|
render()
{
return(
<View style = { styles.MainContainer }>
<TextInput
placeholder = “Enter Product Name”
style = { styles.TextInputStyleClass }
underlineColorAndroid = “transparent”
onChangeText = {(TextInputText) => this.setState({ Product_Name: TextInputText })} />
<TextInput
placeholder = “Enter Product Number”
style = { styles.TextInputStyleClass }
underlineColorAndroid = “transparent”
onChangeText = {(TextInputText) => this.setState({ Product_Number: TextInputText })} />
<TextInput
placeholder = “Enter Product Details”
style = { styles.TextInputStyleClass }
underlineColorAndroid = “transparent”
onChangeText = {(TextInputText) => this.setState({ Product_Details: TextInputText })} />
</View>
);
}
|
8. Create a Custom Button using TouchableOpacity component. We would call the Insert_Data_Into_MySQL() function on this button onPress event.
1
2
3
4
5
6
7
8
|
<TouchableOpacity
activeOpacity = { 0.5 }
style = { styles.TouchableOpacityStyle }
onPress = { this.Insert_Data_Into_MySQL }>
<Text style = { styles.TextStyle }>Insert Data Into MySQL Database</Text>
</TouchableOpacity>
|
8. Create ActivityIndicator inside a Curly bracts block. The ActivityIndicator will only visible on if the ActivityIndicator_Loading state value is True. So it will show on screen at Data inserting time and when the response came from server then it will hide the ActivityIndicator. We are using the Ternary operator to perform this functionality.
1
2
3
4
5
|
{
this.state.ActivityIndicator_Loading ? <ActivityIndicator color=‘#009688’ size=‘large’style={styles.ActivityIndicatorStyle} /> : null
}
|
9. Create CSS Style for All components.
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
|
const styles = StyleSheet.create(
{
MainContainer:
{
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’,
margin: 20
},
TextInputStyleClass:
{
textAlign: ‘center’,
height: 40,
backgroundColor : “#fff”,
borderWidth: 1,
borderColor: ‘#009688’,
borderRadius: 7 ,
marginBottom: 10,
width: ‘95%’
},
TouchableOpacityStyle:
{
paddingTop:10,
paddingBottom:10,
backgroundColor:‘#009688’,
marginBottom: 20,
width: ‘90%’
},
TextStyle:
{
color: ‘#fff’,
textAlign: ‘center’,
fontSize: 18
},
ActivityIndicatorStyle:{
position: ‘absolute’,
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: ‘center’,
justifyContent: ‘center’
}
});
|
10. 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
|
import React, { Component } from ‘react’;
import { StyleSheet, View, TextInput, Text, ActivityIndicator, TouchableOpacity } from ‘react-native’;
export default class App extends Component<{}>
{
constructor()
{
super();
this.state = {
Product_Name: ”,
Product_Number: ”,
Product_Details: ”,
ActivityIndicator_Loading: false,
}
}
Insert_Data_Into_MySQL = () =>
{
this.setState({ ActivityIndicator_Loading : true }, () =>
{
fetch(‘https://reactnativecode.000webhostapp.com/Insert_Product.php’,
{
method: ‘POST’,
headers:
{
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify(
{
product_name : this.state.Product_Name,
product_number : this.state.Product_Number,
product_details : this.state.Product_Details
})
}).then((response) => response.json()).then((responseJsonFromServer) =>
{
alert(responseJsonFromServer);
this.setState({ ActivityIndicator_Loading : false });
}).catch((error) =>
{
console.error(error);
this.setState({ ActivityIndicator_Loading : false});
});
});
}
render()
{
return(
<View style = { styles.MainContainer }>
<TextInput
placeholder = “Enter Product Name”
style = { styles.TextInputStyleClass }
underlineColorAndroid = “transparent”
onChangeText = {(TextInputText) => this.setState({ Product_Name: TextInputText })} />
<TextInput
placeholder = “Enter Product Number”
style = { styles.TextInputStyleClass }
underlineColorAndroid = “transparent”
onChangeText = {(TextInputText) => this.setState({ Product_Number: TextInputText })} />
<TextInput
placeholder = “Enter Product Details”
style = { styles.TextInputStyleClass }
underlineColorAndroid = “transparent”
onChangeText = {(TextInputText) => this.setState({ Product_Details: TextInputText })} />
<TouchableOpacity
activeOpacity = { 0.5 }
style = { styles.TouchableOpacityStyle }
onPress = { this.Insert_Data_Into_MySQL }>
<Text style = { styles.TextStyle }>Insert Data Into MySQL Database</Text>
</TouchableOpacity>
{
this.state.ActivityIndicator_Loading ? <ActivityIndicator color=‘#009688’ size=‘large’style={styles.ActivityIndicatorStyle} /> : null
}
</View>
);
}
}
const styles = StyleSheet.create(
{
MainContainer:
{
flex: 1,
justifyContent: ‘center’,
alignItems: ‘center’,
margin: 20
},
TextInputStyleClass:
{
textAlign: ‘center’,
height: 40,
backgroundColor : “#fff”,
borderWidth: 1,
borderColor: ‘#009688’,
borderRadius: 7 ,
marginBottom: 10,
width: ‘95%’
},
TouchableOpacityStyle:
{
paddingTop:10,
paddingBottom:10,
backgroundColor:‘#009688’,
marginBottom: 20,
width: ‘90%’
},
TextStyle:
{
color: ‘#fff’,
textAlign: ‘center’,
fontSize: 18
},
ActivityIndicatorStyle:{
position: ‘absolute’,
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: ‘center’,
justifyContent: ‘center’
}
});
|
Screenshot in Android device :