How to Insert Text Input Data – store multiple TextInput component entered data to online PHP MySQL database server using Fetch API and Show server response inside app using Alert message after successfully inserted record.
Inserting data from React Native application to MySQL database is a very important task to every developer because without submitting data from app there is no dynamic activity in project. So in this tutorial we would going to create a react native application which would stores the Text Input entered value into MySQL database and after successfully inserting the record it would show us the response conformation message coming from server into Alert message. So let’s get started 🙂 .
Contents in this project Insert Text Input Data To MySQL Server :
1. Create a database + Table on your online hosting server.
Create a database on your MySQL server, then Create a fresh table inside the database. The table name should be UserInfoTable . Add 4 columns inside the table id, name, email, phone_number .
2. Create PHP script to insert received data from React Native application into MySQL database.
Create 2 PHP files DBConfig.php and submit_user_info.php .
DBConfig.php : This file contains the MySQL database hostname, database name, database password and database username.
submit_user_info.php : This file receive the send record from application and insert that received 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 submit_user_info.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 |
<?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 name from JSON $obj array and store into $name. $name = $obj['name']; // Populate email from JSON $obj array and store into $email. $email = $obj['email']; // Populate phone number from JSON $obj array and store into $phone_number. $phone_number = $obj['phone_number']; // Creating SQL query and insert the record into MySQL database table. $Sql_Query = "insert into UserInfoTable (name,email,phone_number) values ('$name','$email','$phone_number')"; if(mysqli_query($con,$Sql_Query)){ // If the record inserted successfully then show the message. $MSG = 'Data Inserted Successfully into MySQL Database' ; // Converting the message into JSON format. $json = json_encode($MSG); // Echo the message. echo $json ; } else{ echo 'Try Again'; } mysqli_close($con); ?> |
3. Start a fresh React Native project. If you don’t know how then read my this tutorial.
4. Add AppRegistry, StyleSheet, TextInput, View, Alert, Button component inside the import block.
1 2 3 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, TextInput, View, Alert, Button } from 'react-native'; |
5. Create constructor.
Create a constructor in your Main Class with props parameter. Now declare three variables TextInputName: ‘ ‘, TextInputEmail: ‘ ‘ and TextInputPhoneNumber: ‘ ‘ with empty values using this.state.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
constructor(props) { super(props) this.state = { TextInputName: '', TextInputEmail: '', TextInputPhoneNumber: '' } } |
6. Create function named as InsertDataToServer() to send the Text Input data on server.
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 |
InsertDataToServer = () =>{ const { TextInputName } = this.state ; const { TextInputEmail } = this.state ; const { TextInputPhoneNumber } = this.state ; fetch('https://reactnativecode.000webhostapp.com/submit_user_info.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ name: TextInputName, email: TextInputEmail, phone_number: TextInputPhoneNumber }) }).then((response) => response.json()) .then((responseJson) => { // Showing response message coming from server after inserting records. Alert.alert(responseJson); }).catch((error) => { console.error(error); }); } |
7. Create custom css class named as MainContainer and TextInputStyleClass just above the AppRegistry.registerComponent line.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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: '#FF5722', // Set border Radius. //borderRadius: 10 , } }); |
8. Add View as parent view in render’s return block and Call the MainContainer class into View.
1 2 3 4 5 6 7 8 9 10 11 |
render() { return ( <View style={styles.MainContainer}> </View> ); } |
9. Add 3 Text Input and 1 Button component inside the View .
placeholder = Shows hint inside the Text Input.
onChangeText = Every time when user type anything in Text Input it will store the entered value in state variable.
underlineColorAndroid = Hide the Text Input base line.
style = Used to call css class.
onPress = Call the InsertDataToServer() function 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 44 45 46 47 48 49 50 51 52 53 |
render() { return ( <View style={styles.MainContainer}> <TextInput // Adding hint in Text Input using Place holder. placeholder="Enter Name" onChangeText={TextInputName => this.setState({TextInputName})} // Making the Under line Transparent. underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput // Adding hint in Text Input using Place holder. placeholder="Enter Email" onChangeText={TextInputEmail => this.setState({TextInputEmail})} // Making the Under line Transparent. underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput // Adding hint in Text Input using Place holder. placeholder="Enter Phone Number" onChangeText={TextInputPhoneNumber => this.setState({TextInputPhoneNumber})} // Making the Under line Transparent. underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <Button title="Insert Text Input Data to Server" onPress={this.InsertDataToServer} color="#2196F3" /> </View> ); } } |
10. Complete source code for index.android.js / index.ios.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 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, TextInput, View, Alert, Button } from 'react-native'; class MainProject extends Component { constructor(props) { super(props) this.state = { TextInputName: '', TextInputEmail: '', TextInputPhoneNumber: '' } } InsertDataToServer = () =>{ const { TextInputName } = this.state ; const { TextInputEmail } = this.state ; const { TextInputPhoneNumber } = this.state ; fetch('https://reactnativecode.000webhostapp.com/submit_user_info.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ name: TextInputName, email: TextInputEmail, phone_number: TextInputPhoneNumber }) }).then((response) => response.json()) .then((responseJson) => { // Showing response message coming from server after inserting records. Alert.alert(responseJson); }).catch((error) => { console.error(error); }); } render() { return ( <View style={styles.MainContainer}> <TextInput // Adding hint in Text Input using Place holder. placeholder="Enter Name" onChangeText={TextInputName => this.setState({TextInputName})} // Making the Under line Transparent. underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput // Adding hint in Text Input using Place holder. placeholder="Enter Email" onChangeText={TextInputEmail => this.setState({TextInputEmail})} // Making the Under line Transparent. underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput // Adding hint in Text Input using Place holder. placeholder="Enter Phone Number" onChangeText={TextInputPhoneNumber => this.setState({TextInputPhoneNumber})} // Making the Under line Transparent. underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <Button title="Insert Text Input Data to Server" onPress={this.InsertDataToServer} color="#2196F3" /> </View> ); } } 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: '#FF5722', // Set border Radius. //borderRadius: 10 , } }); AppRegistry.registerComponent('MainProject', () => MainProject); |
Very Nice Tutorial Sir…
Thanks 🙂
hi admin. thanks for your tutorial. I am facing a problem. I have saved the php files into the xampp/htdocs. and I have called http://localhost/submit_user_info.php but still it is showing Network request failed. need your help. thanks in advanced
Akash you need to create a folder inside htdocs folder and then put the php file inside the folder and add the folder name into URL.
Hi,
Error :’Network request failed’
fetch(‘https://localhost:8000/submit_user_info.php’
How can i solve this?
Thanks
Zan you are using the URL wrong you should use like that : http://YourLocalSystemIpAddpress/submit_user_info.php . You can use IPCONFIG command to find your local system IP address.
Hi, your web is awesome about react native, but i need some tutorial about insert images into mysql with react native and CRUD react native with php mysql, can you help ? thanks
Yes Ipung i will soon upload a new tutorial on CRUD operations.
Message show that data enter successfully but not received any data in my online server database
Imran check your Table column names and other configuration ?
I checked all but not found any problem in that ….can you give me your facebook id for help ?
Imran you can mail me your source code on – [email protected]
Thank your for your support the problem solved and your tutorial is very good I hope you provide more material in future also and its request to kindly provide the CRUD video of react native also
Imran i am currently working on CRUD tutorial. i will soon publish it .
Hello Imran Javed, i am struggling from yesterday, no one is replying, plz tel me how it worked for u…i am facing same problem as u, shown everything on screen of phone but nothing going on database after filling data, i checked all data again n again… i am using linux, put my both .php file in my react native project folder..
Sudhir you need to put the PHP files in localhost/ xampp folder read our this tutorial : https://reactnativecode.com/connect-run-apps-using-localhost/
Thanks a lot dude
Welcome 🙂 .
Where do I put the DBConfig.php and submit_user_info.php?
Do I store those files on the server?
I’m using Xampp, to create and run a MYSQL database. Do you know how I can achieve this?
Cheers
Chris i am using the 000webhost online hosting service. But to run this project on locally using Xampp, You need create a folder inside your Xampp -> htdocs -> YourFolerName . Now put both PHP files inside this folder. Now run the ipconfig command in command prompt to know your local system IP address. Now after finding the IP your URL should look like this : http://YourSystemIpAddress/submit_user_info.php . Use this URL into Fetch() method.
I found the solution.It’s actually in the htdocs folder in xampp, where you can place your php files.
Thanks for the help.
Yes Chris .. Welcome 🙂
Bro if I am using webhost then where should i put php files
Manpal here webhost means online hosting server ? Then you need to put all the PHP files to your hosting space.
Great Tutorial. I made some subtle changes because I think of newer versions of React-Native.
After I run the update I get errors: JSON Parse error: Unexpected identifier “insert” Then a bunch of errors from the core product. I have the submit_user_info.php and the DBConfig on my server.
How would I debug this. Is it the logon, the SQL query etc.
I am using Expo XDE and Genymotion to test this.
Peter check DBConfig file put all the details of your server inside it.
Everything works fine but i get a response JSON Parse error unrecognized token ‘<' instead of user registered succesfully
from the server
Solex you need to check DBConfig.php file for all server configuration and also check your table name in submit_user_info.php . One more thing you are running php script on localhost or online server.
Yeah the problem was in the submit_user_info.php Everything is perfect now thanks admin looking forward to seeing more tutorials Thanks
Welcome Solex 🙂 .
Awesome post,
Your way of explaining is very nice,
Thanks a lot
Thanks Divyanshu 🙂 .
Thank You admin. a very helpful tutorial for react native beginners. i hope you keep working on the amazing content
Thanks Amine 🙂 .
God Job Sir..
I have a problem in local system IP address
This is my IPCONFIG sir, which one should I choose :
Connection-specific DNS Suffix :http://www.huaweimobilewifi.com
Link-local IPv6 Address . . . . . : fe80::3ce5:b38f:cb0:7579%19
IPv4 Address. . . . . . . . . . . : 192.168.1.106
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.1.1
in my source, i type like this :
fetch(‘https://192.168.1.106/submit_user_info.php’
but still find the error ‘Network request failled’
thank for your help, God Bless You…
You should use IPv4 Address .
If i login to sistem di react native, can i get sesseion? Sorry i not good english sir, i have projek can you help me, i will pay u sir
Yes you can use seasons Sudita, to store season you can use AsyncStorage. Read the official documentation on https://facebook.github.io/react-native/docs/asyncstorage.html.
hi,
nice tutorial but I have a qn: what is the python equivalent of =>
$json = file_get_contents(‘php://input’);
thank you!
Sorry dhanush i have no idea about Python .
Sir , if i save my php file in htdocs …is it belong to my react native project because project in on another path
Sandeep if you want to run PHP files then you need to put all the php files in htdocs folder. Now use http://YourWebSiteIP/YourProjectFolder/file.php inside your application.
sir my react native project is in c:/users/admin
if i save my php file in C:/xampp/htdocs….
would my react native project recognise it
Yes sandeep it would because your it will communicate with the URL .
I tried it in localhost, but it gives network error. Could it be because i try in local?
No Berke, check your database config file or make sure when you are testing this project you have connected to internet because fetch works over internet.
Thanks Admin,
These tutorials are really interesting. I have learnt more things. 🙂
Keep it up!
Welcome Bro 🙂 .
Nice tutorial ADMIN!!!
sir i am allready changed from localhost to ip address of system but still i got the same error “network request failed”.
what should i do now ?
fetch(‘http://10.0.2.2/insertReg.php’,
it will work
I just copy all ur code, but nothing is shown on database after filling data in form.
I am using ubuntu, android phone connected to my laptop, using react native 0.55, installed a fresh project of react native through “react-native init app” and put yours these two “submit_user_info.php” and “DBConfig.php” in this project folder….and that react native code is in App.js….after running i got form on my phone screen but nothing updated on database…where i am doing mistake?
whose ip address i have to keep in that portion, phone ip address or laptop ip address? my ip is: 192.168.0.81 how i write it in that format plz tell?
should i write it as ‘https://192.168.0.81/submit_user_info.php’ , here in place of “submit_user_info” what will come?
Hello world
bye world
sir i want this two data to store on a db…. how to do that?
this two data is just a text
Vivek local db or online MySQL db ?
pls i have this issue, JSON Parse error: unrecognize token ‘<'….pls admin can you help with this
Sir please check your database config file .
fetch(‘http://localhost/submit_user_info.php’
Network request failed
Hi, Sr.
I’ve tried to use your URL and DB’s config in my Host but does’t works.
I just upload all the PHP files in my MySQL and I changed the fetch URL to mine, like this : fetch(‘https://appdejore.000webhostapp.com/ShowAllStudentsList.php’ , etc…
It works at web, but when I run in my React Native, doesn’t. A red error appears…
Can i have some help? My host is :
//Define your host here.
$HostName = “localhost”;
//Define your database name here.
$DatabaseName = “id6607105_app_teste”;
//Define your database username here.
$HostUser = “id6607105_app”;
//Define your database password here.
$HostPass = “123456789”;
Login: [email protected]
Password: 1234
What error is coming ?
Hello sir,
Great tutorial! I’m having a problem at the end it seems though 🙁
–> JSON Parse Error: Unrecognized token ‘<'
I've checked both DBConfig.php & submit_user_info.php and can't see a problem…
DBConfig.php below:
Could you help me please
Francois send me your code on [email protected]
your tutorials Ok Mr.. Thanks
Hi sir, I having a problem that I only can insert one data. If I insert two data I will have a problem at the end it seems though
–> JSON Parse Error: Unrecognized token ‘Try’
Did you follow all my steps ? Or maybe there is something wrong in SQL insert query bro .
I solve the proplem already,thankyou. But now i am facing the problem with Network request failed.
I have follow all the step in https://reactnativecode.com/react-native-user-login-using-php-mysql/?fbclid=IwAR23IBhLkjooLMY_qm5Cw7mCyYfuTFm-ZSPBg0dIyHjVUo3aP5qjMgnZftg
Network request fail is mostly comes when you put the serve URL without IP .
I put already my ip address but still have error
JSON Parse error: Unrecognized token'<' can someone please tell me how to fix this error
Jones try to make same database field name .
fetch(‘http://103.40.2.2/register.php’, {
method: ‘post’,
header:{
‘Accept’: ‘application/json’,
‘Content-type’: ‘application/json’
},
body:JSON.stringify({
name: userName,
email: userEmail,
password: userPassword,
})
})
.then((response) => response.json())
.then((responseJson) =>{
alert(responseJson);
})
.catch((error)=>{
console.error(error);
});
//this is what i have
Jones send your app.js and php file code to me on [email protected] along with database table screenshot.
i fixed it thanks
Welcome 🙂 .
yntaxError: Unexpected token < in JSON at position 0. help!
Nicolas please check that in the database config file you have put the right database username and password of your MySQL database.
data is submit successfully in database , but database is receive empty column .
in reactjs
Check the receiving tags is same on your php files.
i can Check the receiving tags,
it is same on my php files.
hello,admin can u please provide code for verification of registration using mysqldatabase
Kamana please explain code for verification means ? Like mail verification or sms verification ?
please how do i get my the specifications of my xampp database