User registration is a simple process to register some particular user information on server, which will be used again when user trying to Log-in into application. Like User Name, Password, Email etc. So in this tutorial we would going to create an react native android and iOS application with complete user registration process on our online hosting server using PHP MySQL. This type of application also known as API.
Database used in this tutorial : MySQL
Server Side scripting Language used in this tutorial : PHP
Important Note : This code is working correctly in both Android and iOS devices. So feel free to create your own User Registration Authentication application for Android and iOS using my this tutorial 🙂 .
Contents in this project React Native User Registration With PHP MySQL :
1. Create a Database + Table on your hosting server :
Create a database on your MySQL server, then Create a fresh table inside the database. The table name should be UserRegistrationTable . Add 4 columns inside the table id, name, email, password.
2. Create PHP Script to insert user registration information received from App into MySQL database :
Create 2 PHP files DBConfig.php and user_registration.php .
DBConfig.php : This file contains the MySQL database hostname, database name, database password and database username.
user_registration.php : This file receive the user registration information and insert that info 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 user_registration.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 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<?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 name from JSON $obj array and store into $name. $name = $obj['name']; // 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']; //Checking Email is already exist or not using SQL query. $CheckSQL = "SELECT * FROM UserRegistrationTable WHERE email='$email'"; // Executing SQL Query. $check = mysqli_fetch_array(mysqli_query($con,$CheckSQL)); if(isset($check)){ $EmailExistMSG = 'Email Already Exist, Please Try Again !!!'; // Converting the message into JSON format. $EmailExistJson = json_encode($EmailExistMSG); // Echo the message. echo $EmailExistJson ; } else{ // Creating SQL query and insert the record into MySQL database table. $Sql_Query = "insert into UserRegistrationTable (name,email,password) values ('$name','$email','$password')"; if(mysqli_query($con,$Sql_Query)){ // If the record inserted successfully then show the message. $MSG = 'User Registered Successfully' ; // 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, Text component inside the import block.
1 2 3 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, TextInput, View, Alert, Button, Text } from 'react-native'; |
5. Create constructor.
Create a constructor in your Main Class with props parameter. Now declare three variables UserName: ‘ ‘, UserEmail: ‘ ‘ and UserPassword: ‘ ‘ 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 = { UserName: '', UserEmail: '', UserPassword: '' } } |
6. Create function named as UserRegistrationFunction() 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 36 37 |
UserRegistrationFunction = () =>{ const { UserName } = this.state ; const { UserEmail } = this.state ; const { UserPassword } = this.state ; fetch('https://reactnativecode.000webhostapp.com/user_registration.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ name: UserName, email: UserEmail, password: UserPassword }) }).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 24 25 26 |
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 , // 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 and 1 Text 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 UserRegistrationFunction() 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 54 55 56 57 |
render() { return ( <View style={styles.MainContainer}> <Text style= {{ fontSize: 20, color: "#000", textAlign: 'center', marginBottom: 15 }}>User Registration Form</Text> <TextInput // Adding hint in Text Input using Place holder. placeholder="Enter User Name" onChangeText={UserName => this.setState({UserName})} // Making the Under line Transparent. underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <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 Register" onPress={this.UserRegistrationFunction} 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 138 139 140 141 142 143 144 |
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, TextInput, View, Alert, Button, Text } from 'react-native'; class MainProject extends Component { constructor(props) { super(props) this.state = { UserName: '', UserEmail: '', UserPassword: '' } } UserRegistrationFunction = () =>{ const { UserName } = this.state ; const { UserEmail } = this.state ; const { UserPassword } = this.state ; fetch('https://reactnativecode.000webhostapp.com/user_registration.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ name: UserName, email: UserEmail, password: UserPassword }) }).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}> <Text style= {{ fontSize: 20, color: "#000", textAlign: 'center', marginBottom: 15 }}>User Registration Form</Text> <TextInput // Adding hint in Text Input using Place holder. placeholder="Enter User Name" onChangeText={UserName => this.setState({UserName})} // Making the Under line Transparent. underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <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 Register" onPress={this.UserRegistrationFunction} 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: '#2196F3', // Set border Radius. borderRadius: 5 , // Set border Radius. //borderRadius: 10 , } }); AppRegistry.registerComponent('MainProject', () => MainProject); |
Screenshots in iOS device :
Screenshot in Android Device :
Screenshot of MySQL database table after user registration :
Hi,
You passed into the fetch api ‘https://reactnativecode.000webhostapp.com/user_registration.php’.
What should I pass in for the php file on my local server?
I am not familiar with php so I need your help on this. Thanks!
Hey May, if you using localhost then your url should be YourSystemId/PhpPagename .
I put it as localhost/user_registration.php
And when I click the registration button it says Network Request Fail
I think I have gotten the system id wrong. How do I know what is the id?
Oh I think I have found the name with the command SHOW VARIABLES WHERE Variable_name = ‘hostname’;
But where do I save the 2 php files so that they can be accessed? Currently it still says Network Request Fail when I click the registration button.
Okay, I think I found where to save the files to, ie Macintosh HD > Users > MyUserName.
I placed the php files there and when I ran the app again in Expo it says JSON Parse error: Unrecognized token: ‘<'
May just install the Xampp in your MAC, then put the php files in xampp-> htdocs folder. Now use your system’s IpAddress/phpfiles as url in fetch method.
Hey admin, im so happy to stumbled upon this tutorial
thanks a lot for sharing
however i found and error on inserting after following every exact step
for fetching i use http://127.0.0.1/react/user_registration.php
but its still error
itd be appreciated a lot to have your thought regarding this issue
What error you have facing ?
Ah thanks for this solution. I tried your previous solution on using the web host and it works too. You’ve been really helpful!
Will you be creating a tutorial on logging in soon?
May i have just posted a new tutorial about Login using PHP MySQl : https://reactnativecode.com/react-native-user-login-using-php-mysql/
Oh thanks so much! I appreciate how you are really responsive to my questions and request. I will continue to visit your website to learn from your tutorials. (:
Thanks May 🙂
thank you for information.it is helpfull to me.
Tutorial is really very good, but still i dont know where to put 2 .php files? can you please tell me? or if you have any video tutorial then it will be better, thank you in advance.
Rohit you need to put PHP files on your hosting server or if you are using localhost then inside the xampp -> htdocs folder.
sorry to disturb you but i didnt get what exactly i put in fetch(‘http://localhost/user_registration.php’)
first time it shows “User Registered Successfully”
second time it showing “Email Already Exist, Please Try Again !!!”
but still database not having any values
From program to database value is not passing here, for sample i making
fetch(‘http://ipAdd:80/user_registration.php’, {
method: ‘POST’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
name: ‘Rohit Patil’,
email: ‘[email protected]’,
password: ‘[email protected]’
})
Everything working properly on ubuntu localhost machine,
now i want to put my all php script files in windows server, where do i put them in microsoft sql server, so that i can access it from my local ubuntu machine? is it possible?
Rohit here windows server means your online hosting or in local windows system ?
I have to do on both ,
but firstly on local windows system and then online hosting.
Rohit then you need to install Xampp on your windows system then It will create a folder in C drive named as Xampp -> htdocs , Now create a folder in htdocs folder and put your .PHP files inside it. Now open the web browser Google chrome or Mozilla type localhost/YourFolderName . Here you go now your php files would run.
where exactly is the xampp folder?
Or do i have to create one ?
*I am using macOS
The Xampp folder will be created in your C drive after installing Xampp software in your computer.
Thank you So much now its working…
Now i am having two problems please give me solution:
1. how do i post images in same way, now only text is send.
2. now i am working on local machine(Ubuntu) but how mysql will work on remote server machine(Windows)
If you have solution please inform me [email protected]
Testing this with android emulator and following error occurs:
“JSON Parse error: Unexpected EOF”
Have you seen this error message before? any idea where could be related?
Hello,
The problem was in my dbconfig -php file. It was my mistake, there was an extra character I added accidentally.
Thanks for the great tutorial!
Welcome Tyrni 🙂
Help me, please: JSON Parse error: Unrecognized token'<'
Caio check your dbconfig file.
wes tak cek kok durung iso ?
Yes i have checked it with iOS device.
i added two php files in htdoc folder ….but …Currently it still says Network Request Fail when I click the registration button.
Naveen you need to create a folder inside htdocs -> YourFolder . Now make the URL like http://localhost/YourFolder/YourFileName.php . Use this URL in react native code.
I use this but i still getting the network request failed
Hi, great tutorial!
You are using
fetch(‘https://reactnativecode.000webhostapp.com/user_registration.php’,…
I’m using mysql with phpadmin and my *.php files are saved on gitlab. What do I have to put into fetch as URL? I get an error when i’m using the gitlab url
Yannik you need to call the user_registration.php file URL in fetch. before putting the URL in fetch open this URL in web browser to make sure this is working.
In case anyone comes across the ‘unrecognized token ‘ response.json())
.then((responseJson) => {
// Showing response message coming from server after inserting records.
Alert.alert(responseJson);
}).catch((error) => {
//console.error(error);
});
To get it to work. Something to do with it trying to output html. Not sure why it’s hitting this error though. It successfully inserts into my online mysql db.
Thanks for comment Chris 🙂
Thank you Admin for this tutorial
Welcome Ravi 🙂 .
when I used this code I got error JSON Parse error: Unrecognized token: ‘<' and I don't know what is the solution.
I am using localhost:88 show in that db.php what i have to give
localhost or localhost:88
Ashish if your testing this code on Local system then you must use this type of URL http://YourWebsiteIpAddress/yourFile.php .
yes I tried but still I get same problem.
Can I know http://YourWebsiteIpAddress/yourFile.php this one “/yourFile.php” is pointing what php file?
It is pointing to user_registration.php file.
I’m getting this too. I’m pretty sure I have done it exactly how you have put it. Everything that I have read seems to say its receiving html and not JSON.
Aubrey please check your MySQL configuration ?
I have found the problem. I needed to change the hostname in DBConfig.php from local host to my ip address as well. Not sure if you may want to point that out in the tutorial.
Thanks for the great resource btw! I have learned heaps!
Welcome Aubrey 🙂 .
And now I cannot get it working properly when I have the mysql on an external server, 🙁
It’s doing the same thing as it was before, any ideas?
Aubrey just put your hostname in host name and put PHP files on server.
when i do that I get “syntaxError: JSON Parse error: Unrecognized token ‘<' " again
Aubrey please check your server configuration in DBConfig.php file.
Hi Admin, Thanks. I see what the issue was, I had to use the public ip in the app and then on the DBConfig.php had to use the local network ip.
Again, this has forced me to learn more and I thank you for that!
Welcome Aubrey and please like our Facebook page to help us growing 🙂 .
Hi,
I’m sorry to ask the same question that 100’s before me already did. But I get Network request failed. I’ve stored my .php files in www in my wamp and it looks like I get access to the database from those files (open localhost/MyFolder/user_registration.php) and gets a result, albeit a “try again” message. I guess though that that’s because I have no data in the call.
Fixed the initial problem. I hadn’t checked AI for ID so that wasn’t inserted automatically. Now my php seems to work, and I can access it, but my app still gets Network request failed.
Jonathan you need to use URL like this http://YourSystemIpAddress/file.php .
One more update. Obsiously localhost wont work since I’m testing it on my phone… However using my local IP doesn’t work either. Shouldn’t I be able to use my local IP or do I have to use the IP of my router and port forward to my computer?
network request failed i am facing this problem. i think this is for the link i used. i cannot understand how i get the system id of localhost
http://localhost/reactnative/registration2.php i have kept the user_registration.php as registration2.php. i also kept the reactnative folder in localhost. can you tell me what will be the link
Sharif you need to use URL like this http://YourSystemIpAddress/file.php .
Hi
I have an error when i us my link
Please help.
ExceptionsManager.js:73 SyntaxError: Unexpected token T in JSON at position 0
at parse ()
at tryCallOne (core.js:37)
at core.js:123
at JSTimers.js:301
at _callTimer (JSTimers.js:154)
at _callImmediatesPass (JSTimers.js:202)
at Object.callImmediates (JSTimers.js:470)
at MessageQueue.__callImmediates (MessageQueue.js:329)
at MessageQueue.js:147
at MessageQueue.__guardSafe (MessageQueue.js:316)
Rollano please check your database config file .
Sir ……. i just do what you did in this tutorial
1.install xampp and make a database in it.
2.Then i create a react native project in htdocs folder of xampp
3. Then i code what you code ….
But i got stuck in fetch (http:/????/.php);
you said used your local ip address … in cmd after writing ipconfig
i found ipv4 ip address i just copy this in my fetch … but it showing error????
please help….
Vivek if you are connected to WiFi then use your IPv4 address under WiFi area and if you are connected to Broad band using port then use Ethernet IPv4 address, If you still face any problem then please tell me 🙂 .
sir should i move my whole project into htdocs
Yes, Vivek you need to move the complete project into Htdocs -> Your_Project_Folder.
Sir, it shows development server return response error 500…….what to do?????
Vivek shut down your emulator and again restart it and execute react-native run-android command.
Here is the code sir please check is everything okay?
import React, { Component } from ‘react’;
import { AppRegistry,
StyleSheet,
TextInput,
View,
Alert,
Button,
Text } from ‘react-native’;
const App = () =>{
constructor(props)
{
super(props)
this.state = {
UserName: ”,
UserEmail: ”,
UserPassword: ”
}
}
UserRegistrationFunction = () =>{
const { UserName } = this.state ;
const { UserEmail } = this.state ;
const { UserPassword } = this.state ;
fetch(‘https://192.168.1.1/user_registration.php’, {
method: ‘POST’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
name: UserName,
email: UserEmail,
password: UserPassword
})
}).then((response) => response.json())
.then((responseJson) => {
// Showing response message coming from server after inserting records.
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});
}
return (
User Registration Form
this.setState({UserName})}
// Making the Under line Transparent.
underlineColorAndroid=’transparent’
style={styles.TextInputStyleClass}
/>
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}
/>
);
}
export default App;
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 ,
// Set border Radius.
//borderRadius: 10 ,
}
});
Vivek you are using wrong syntax,
You are using const App = () =>{
instead ofexport default class MainProject extends Component {
. So just use thisexport default class MainProject extends Component {
at the starting of application.Thank you for answer
I have double check my config… everything like good 🙁
Sir on which platform you are running your code means Using local host or Using online hosting ?
Sorry i am using online hosting
Rollano you need to upload all the PHP files on your hosting server and call them with your domain name like i have done in this tutorial.
I do exactly that. the files are in my ftp server.
Database spécialy created for this tutorial
Rollano please send your URL to me .
https://taekwondo-asnieres.com/APP/test/user_registration.php
Rollano your url is working fine, send me your app code .
export default class SignUpForm extends Component {
constructor(props) {
super(props);
this.state = {
UserName: ”,
UserPrenom: ”,
UserEmail: ”,
UserPassword: ”,
UserClubName: ”,
UserRole: ”,
};
}
UserRegistrationFunction = () => {
const { UserName } = this.state;
const { UserPrenom } = this.state;
const { UserEmail } = this.state;
const { UserPassword } = this.state;
const { UserClubName } = this.state;
const { UserRole } = this.state;
fetch(‘https://taekwondo-asnieres.com/APP/test/user_registration.php’, {
method: ‘POST’,
headers: {
Accept: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
name: UserName,
prenom: UserPrenom,
email: UserEmail,
password: UserPassword,
clubName: UserClubName,
role: UserRole,
})
}).then((response) => response.json())
.then((responseJson) => {
// Showing response message coming from server after inserting records.
if (Platform === ‘Android’) {
Alert.alert(responseJson);
} else {
AlertIOS.alert(responseJson);
}
}).catch((error) => {
console.error(error);
});
}
render() {
return (
this.setState({ UserName })}
placeholderTextColor=”rgba(255,255,255,0.7)”
returnKeyType=”next”
onSubmitEditing={() => this.prenomInput.focus()}
//keyboardType=”email-address”
autoCapitalize=”none”
autoCorrect={false}
/>
this.setState({ UserPrenom })}
placeholderTextColor=”rgba(255,255,255,0.7)”
returnKeyType=”next”
onSubmitEditing={() => this.emailInput.focus()}
//keyboardType=”email-address”
autoCapitalize=”none”
autoCorrect={false}
ref={(input) => this.prenomInput = input}
/>
this.setState({ UserEmail })}
placeholderTextColor=”rgba(255,255,255,0.7)”
returnKeyType=”next”
onSubmitEditing={() => this.passwordInput.focus()}
keyboardType=”email-address”
autoCapitalize=”none”
autoCorrect={false}
ref={(input) => this.emailInput = input}
/>
this.setState({ UserPassword })}
placeholderTextColor=”rgba(255,255,255,0.7)”
onSubmitEditing={() => this.clubNameInput.focus()}
secureTextEntry
returnKeyType=”next”
ref={(input) => this.passwordInput = input}
/>
this.setState({ UserClubName })}
placeholderTextColor=”rgba(255,255,255,0.7)”
onSubmitEditing={() => this.roleInput.focus()}
returnKeyType=”next”
//keyboardType=”email-address”
autoCapitalize=”none”
autoCorrect={false}
ref={(input) => this.clubNameInput = input}
/>
this.setState({ UserRole })}
placeholderTextColor=”rgba(255,255,255,0.7)”
//keyboardType=”email-address”
autoCapitalize=”none”
returnKeyType=”go”
autoCorrect={false}
ref={(input) => this.roleInput = input}
/>
SIGN UP
);
}
}
please…
🙁
Rollano send me your app.js file code on [email protected]
sir finally its working im getting data in my database but its showing error on my emulator
sir finally its working im getting data in my database but its showing error on my emulator….what to do
Sanjeev what error it is showing ?
can you share the source code for better understanding.
Ani all the source code of PHP files and React Native project file is present in this post.
Hi , i’m using WampServer on Windows 10. i did as you mentionned but i get a Network Request Failed error .
I created a folder called “/react” under “C:\wamp64\www\react” and put the .php files there .
when i put “localhost/react” in my browser i can see the .php files .
i changed the URL to : ‘http://localhost/react/user_registration.php’
But i’m still getting that error .. i’m not sure what i’m doing wrong here
Bro you need to use http://YourSystemIpAddress/react/user_registration.php type URL in fetch() .
hi dear
how to download this codes?
i want copy codes but don’t copy!!
Amir trying to refresh the page and the code will be copied easily.
admin,
Can you please guide me how to connect react native app with phpmyAdmin. As i get 401 error when try to connect my app using xampp.
Hammad you need to put the PHP files inside localhost/YourProjectFolder/AllPhpFiles
Now use the ipconfig command to find the local ip of your system and with the URL you should look like this type of URL :
http://yourIP/yourPHPfile.php .
Hi
I use http://localhost/user_registration.php
but first time i have “User Registered Successfully”
second time “Email Already Exist, Please Try Again !!!”
What is the problem ?
Avi first of all the URL should be http://YourLocalIpAddress/user_registration.php and if it will giving you the Email Already Exist, Please Try Again that means the email you have entered is already present inside the database.
I have network request failed
Avi check your database config file .
If my database is empty, when i put http://localhost/user_registration.php on the navigator i have “User Registered Successfully” and this is create an user with empty email
If i put the link a second time i have “Email Already Exist, Please Try Again !!!”
But in the application I have “Network request failed”
Avi send us your both PHP and App code on [email protected]
Okay
I cant send you the mail I have : This message was blocked because its content presents a potential security issue. Please visit https://support.google.com/mail/?p=BlockedMessage to review our message content and attachment content guidelines. i14si7093465pgf.284 – gsmtp
Finaly its good the mail is send
Sorry to disturb you
Hi am continuously getting the error :
Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it’s defined in, or you might have mixed up default and named imports.
This error is located at:
in RCTView (at View.js:60)
in View (at AppContainer.js:102)
in RCTView (at View.js:60)
in View (at AppContainer.js:122)
in AppContainer (at renderApplication.js:32)
throwOnInvalidElementType
ReactNativeRenderer-dev.js:4706:4
createFiberFromElement
ReactNativeRenderer-dev.js:4663:42
reconcileSingleElement
ReactNativeRenderer-dev.js:8338:8
reconcileChildFibers
ReactNativeRenderer-dev.js:8422:14
reconcileChildrenAtExpirationTime
ReactNativeRenderer-dev.js:8622:8
reconcileChildren
ReactNativeRenderer-dev.js:8603:6
updateHostComponent
ReactNativeRenderer-dev.js:9001:22
beginWork
ReactNativeRenderer-dev.js:9589:10
performUnitOfWork
ReactNativeRenderer-dev.js:12924:25
workLoop
ReactNativeRenderer-dev.js:12953:43
renderRoot
ReactNativeRenderer-dev.js:12996:17
performWorkOnRoot
ReactNativeRenderer-dev.js:13632:34
performWork
ReactNativeRenderer-dev.js:13545:26
performSyncWork
ReactNativeRenderer-dev.js:13506:16
requestWork
ReactNativeRenderer-dev.js:13392:6
scheduleWorkImpl
ReactNativeRenderer-dev.js:13259:24
scheduleWork
ReactNativeRenderer-dev.js:13207:28
scheduleRootUpdate
ReactNativeRenderer-dev.js:13930:17
_updateContainerAtExpirationTime
ReactNativeRenderer-dev.js:13966:6
updateContainer
ReactNativeRenderer-dev.js:13991:8
render
ReactNativeRenderer-dev.js:14726:35
renderApplication
renderApplication.js:49:21
run
AppRegistry.js:102:10
runApplication
AppRegistry.js:194:26
__callFunction
MessageQueue.js:351:47
MessageQueue.js:116:26
__guardSafe
MessageQueue.js:314:6
callFunctionReturnFlushedQueue
MessageQueue.js:115:17
Abhi send your all source code on [email protected] , we will check it.
Hey admin
I uploaded php files to host server and wrote fetch(‘https://lifestormphp.000webhostapp.com/user_registration.php’ but it still doesn’t work
Please help me, how can I fix it?
Andrey i have checked your URL it is not working and showing 404 Error, Please check you code.
I sent my code to your email, can you please check it?
Hey admin
Know the URL works, thanks, but it shows error that I have wrong user and password in DBconfig.
Where can I in phpmyadmin my exact hostname, username and password?
Andrey you need to put your online hosting server HostName and database username and password inside it.
i have same error which abhi got also send u email with code
Hey admin
I uploaded php files to my host server and wrote fetch(‘https://lifestormphp.000webhostapp.com/user_registration.php’, but everytime when I press the button submit I receive this mistake: “Unexpected token < in JSON at position 0"
Can you check somehow if my host server works to you?
And how can I fix it?
Hey admin,
I sent you my files to your email.
Please check it.
Thank you
SyntaxError:JSON Parse error :
Unrecognied token ‘<'
Prince check your database config file .
Hey admin
I fixed the link and now it works, but now I receive following mistake: JSON Parse error: Unexpected identifier “Try”
Can you please help me how I can fix it?
Thank you
I fixed everything!
Just forgot to apply a boolean by id on my database 😀
Thank you for this perfect tutorial!
Thanks for notifying us Andrey 🙂 . Glad to know that you liked our website 🙂 .
What do you mean by applying a boolean by id?
Hi..having same issue..can you help how to fix it?
You keep saying check the config file, but what are we checking for? Maybe this is why some people repeated this error. And where do we find this file, if not using Xaamp or Wamp but a live database?
Sally we have to create a config php file named as DBConfig.php and put this file with user_registration.php file. THE DBConfig.php file contains all the server information live what is your database name and database password etc. You need to put all your server details here inside this file and remove my old details from it.
I don’t know what happen to my sourcecode, i’ve check my DBConfig due to many issues that exist above. But, i get different error log :
JSON Parse Error: Unexpected identifier “Try”
what should i do? Thanks in advance.
Thats for react native in expo or android studio?
This is for both use expo and studio.
When I try to register, an alert appears: undefined
Heliton please check the dbconfig file and make sure you have put the right server username and password and on which platform you are testing this code ?
Hi..I followed each step in an empty expo project.Got this error
JSON Parse Error: Unexpected identifier “Try”
what should i do? Thanks in advance.
I am using Mamp.
NIPA i have tested this app with online 000webhost hosting server and its working properly can you send your code on [email protected] . I will check it .
Hi thank you for prompt reply.It is fixed now,I have not checked A_I field last time.It is perfectly working now.
Thank you for the wonderful tutorial.
Can you make a live chat app with react native and php for multiple user role like Doctor and patient?
Thanks for your suggestion NIPA, i will look into your topic and soon publish a new tutorial regarding to your query 🙂 .
I am struggling with user roles.I created a table filed called user type.Once login or register my user need to be in different component based on value selected for user_type Field.
I have used componentDidMount() ..nothing happened.
Can I put any condition on responseJson.
Like the code below:
.then((response) => response.json())
.then((responseJson) => {
if { (user_type is “customer”)
.then.this.props.navigation.navigate(‘customerHome’) }
else
.then.this.props.navigation.navigate(‘App’) }
}).catch((error) => {
console.error(error);
});
Mike to be more specific you want to give functionality on your app like Admin roles and user roles.
Hi.. I followed each step and still got this error SyntaxError:JSON Parse error :
Unrecognized token ‘<'
how to fix it ?
Check the database config file bro and put your server username password there.
this is the error am facing bro, i have debugged and i really dont know what to do again:
Error in C:\Users\olakeji\my-app\src\Lecturers\AddStudents.js: C:/Users/olakeji/my-app/src/Lecturers/AddStudents.js: Unexpected token, expected , (34:33)
32 |
33 |
> 34 | fetch(‘192.168.100.8/insert.php’ {
| ^
35 | method: ‘POST’,
36 | headers: {
37 | ‘Accept’: ‘application/json’,
Please tell me on which server you are testing the app like local server oronline web server.
i need your help Sir everything is working fine but in sql table id increment all the time but data name , email etc not add in table.
and get response of success.
please help 🙂
Hamza check the database config file.
help me Sir
Thanks Sir for the tutorial . I am getting a network fail issue .
Both the php files are placed in xamp/htdocs . When tested them using http://localhost/reg2.php or http://ipaddress/reg2.php The file is working well.
But when I keep it in the fetch thing in react native i.e. fetch(‘http://localhost/reg2.php’) or fetch(‘http://ipaddress/reg2.php’) i am continuously getting the error Unhandled Promise rejection
type error : Network request failed.
When i saw some comments they were like as u are testing on phone localhost//reg2.php wont work . What shall I do sir . Stuck on this error from 2 days . Anyone else who knows the solution may mail me to [email protected].
Any help would be highly appreciated.
Bharath can you send me your all source code on [email protected] , I will run your code and check it & one more thing please notify me in the comment after sending the mail 🙂 .
i.e localhost/reg2.php
Sorry for the whole mess solved that problem .
got an error SyntaxError:JSON Parse error :
Unrecognized token ‘<' . Where is the config file where i have to enter my username ? I am now running my mysql server n bynet.host
Bharath the config file is in the tutorial named as DBConfig.php . You have to put your own server database username and password in the file.
Vlue for title cannot cast from readble native array to string error is displayed
Please explain your query .
[Unhandled promise rejection: TypeError: undefined is not an object (evaluating ‘_react.console.error’)]
* Screens\SignUp.js:49:14 in
– node_modules\promise\setimmediate\core.js:37:14 in tryCallOne
– node_modules\promise\setimmediate\core.js:123:25 in
– … 8 more stack frames from framework internals
Tanmay did you change my code or used is as it is ?
plz help for the above mentioned error.
Hi Admin,
I did exactly the same. I have my Wamp server and I put my .php files in Wamp’s www repertory, in a folder named “ppe”.
In my DBConfig file, I have “localhost” as my hostname, “root” as hostuser and “” as hostpass.
In my .js file, I have a fetch request : “fetch(‘http://172.20.10.14/ppe/user_registration.php’ , {
method: ‘POST’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
….. etc
Here 172.20.10.14 is my IPv4 IP address.
When I run my code and click on the register button, I get “Network Request Failed”.. I don’t know what I did wrong..
Can you help me ??
Camille you are testing the code in emulator or real device ?
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in
C:\xampp\htdocs\harkalay\admin\api\registration.php on line 28
“User Registered Successfully”
Any help??
Shady did you put your own database username password and host name in database config file ?
please i want a user to login once not everytime i open the app, like instagram and other apps.Can you please help me
I think what i want is cookies
i want my user to login once not everytime the app opens.I think its cookies,can you help me with that.
Adroit you can do this simply by storing a key value in application storage using AsyncStorgage which works like cookies, When you successfully login then store the key value an on every time when user open the application then check the key value and if the key present then directly login the user.
ese codigo lo puedo usar para una base de datos de sql server ?
Luis this code is tested and running on MySQL server.
Hi great tutorial but I’m still getting “Network Request Failed”. Can you help me with solving this?
Bharath what changes you have made in project ?
Hi, nice tutorial, exactly what I’m looking for. But the passwords are stored in clear, have you a way to pass and store it encrypted ?
Thanks !
Welcome mike and thanks for your suggestion, i will soon make a tutorial to encrypt the password.
commenting port
Thanks ! I will appreciate it. I’ve tried to hash the password “locally” with argon2, scrypt or bcrypt but none of these methods was a successful. I didn’t succeed to install/import library into my reactnative project.
I can able to register without password, how to fix it? i am using your code only.
Supriya could you send me your code on [email protected] . i’ll check your code .
Hello, I am receiving Alert Error! Try Again. I am using an online server on 000webhost. I have changed the config file to match my DB.
<?php
//Define your host here.
$host_name = "localhost";
//Define your database name here.
$database_name = "id10660839_database";
//Define your database username here.
$host_user = "id10660839_user123";
//Define your database password here.
$host_password = "user321";
my website is
https://thecriticalapp.000webhostapp.com/user_registration.php
I have copied your information exactly with the change of the fetch going to the above URL and changed the config file.
Thank you for your time
Thomas what error is coming in Alert ?
Sorry the information above is for the wrong project please disregard
Hello!
Need help implementing a simple personal account, can you help?
Send your personal account working code with registration and authorization + sql and php files.
Sergey all the code is already here you just have to make your own changes and use the code .
Thank you for sharing the code, but when i click register it show network request failed. I have check my db config but still don’t know what is the prob. How can i fix the error?
Khalidah on which platform you are testing the code like locally or online server ?
Online server brother
Bro on your server please put your own server locahost name because in many cases the host name is different than localhost. And also put all your server details. If you still face the error then share your hosting URL with me.
Think you brother. This tutorial is verry helpfull.
But i have something to ask.
Will my app and my php file be secured?
Yes your app will completely secure. But all you have to do is don’t tell anyone about your URL and you cal also implement root login using URL.
Hi Admin..im getting Network request failed error, i’m working on a local machine and using machine’s IP address..Help me below is ma code
//////
import React, { Component } from ‘react’;
import { AppRegistry, StyleSheet, TextInput, View, Alert, Button, Text } from ‘react-native’;
export default class Register extends Component {
constructor(props) {
super(props)
this.state = {
UserName: ”,
UserEmail: ”,
UserPassword: ”
}
}
UserRegistrationFunction = () =>{
const { UserName } = this.state ;
const { UserEmail } = this.state ;
const { UserPassword } = this.state ;
fetch(‘https://Machine_IP_address/react_projects/mobile/User_Login.php’, {
method: ‘POST’,
headers: {
‘Accept’: ‘application/json’,
‘Content-Type’: ‘application/json’,
},
body: JSON.stringify({
name: UserName,
email: UserEmail,
password: UserPassword
})
}).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 (
User Registration Form
this.setState({UserName})}
// Making the Under line Transparent.
underlineColorAndroid=’transparent’
style={styles.TextInputStyleClass}
/>
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}
/>
);
}
}
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 ,
// Set border Radius.
//borderRadius: 10 ,
}
});
// AppRegistry.registerComponent(‘Register’, () => Register);
//////
Hi Admin..I think i have done all well but still getting Network request failed error..I’m using localhost
thanx for the instructions, it’s working fine
but i’m facing an arabic letters issue 🙁
even i’m using the utf8-general-ci
it stores arabic letters like this
نكتاب ان. زوىكنا
how can i fix it?
I solved it by adding this line after the connection string
$con->set_charset(“UTF8”);
thank you
Mohamed you want to use arbic letters in react native app ?
Sir, i have placed my php files at xampp->hddocs folder and use fetch(http://localhost/Registration/user_registration.php) but getting the error of Network request failed
Should i keep the whole project in hddocs folder or just the php files???
Hassan you have to put your project in Htdocs folder then use the URL .
when I click Register button I get TypeError: Network request faild,
pls help me how i solve it.
Anyone facing error Network request fail. Please, check your local ipaddress via your cmd: enter “ipconfig” and check the IPv4 Address.
Copy the IPv4 address and use for your fetch(‘http://192.168.-.—/folder/filename.php’
using localhost cause misconception while communicating on both networks rather use the ip Address.
i had an errror callled”network request failed”,i did the sameas you were telling people how to put these php files in xamp/htdocs directory,but still i got the same error.Please help me