Our this tutorial has a special purpose between developers, because many of our visitors wanted to test react native apps using Local PhpMyAdmin MySQL database and most of them doesn’t know how to? So in this tutorial we would going to create simple User Registration with Local PhpMyAdmin MySQL Database application in both iOS Android devices example tutorial. We would explain each and every step in this tutorial so don’t skip any step read the tutorial to end. Happy Reading 🙂 .
Contents in this project User Registration with Local PhpMyAdmin MySQL Database iOS Android Example Tutorial:
1. The first step is to install the Local PHP server software in your computer, We are using the XAMPP in our tutorial, So if you have n’t install the XAMPP then download from its official website , It’s free.
2. After installing the XAMPP just start the Apache and MySQL server.
- Next step is to create MySQL database in your local host PhpMyAdmin, So open your web browser(Google chrome, Mozilla Firefox etc.) and type localhost/phpmyadmin and press enter, Now you’ll see the Localhost/PhpMyAdmin MySQL database control panel.
- Click on New link to create new MySQL database.
- Enter the Database name, we are creating the Database named as test.
- Next step is creating Table in your Local database, Enter table name as user_details with columns 4.
- Enter columns name id, name, email, password with type INT and VARCHAR. Now make the id as auto increment and make the id is primary key.
- Now the table creating part is done, Next step is start coding for PHP server files.
4. Creating PHP Files:
we have to create 2 php files first one is dbconfig.php and second is user_registration.php .
Code for dbconfig.php file:
This file contains all the most useful information about our server like server database username, host name, password and database name.
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 = "test"; //Define your database username here. $HostUser = "root"; //Define your database password here. $HostPass = ""; ?> |
Code for user_registration.php file:
This file is used to insert user registration information data into MySQL database table. We would call this file into our react native code.
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 user_details 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 user_details (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); ?> |
5. Create a folder name as User_Project inside C:\xampp\htdocs\ like i did in below screenshot and copy the both dbconfig.php and second is user_registration.php PHP files inside this folder. We would now call these files with IP of our local system.
6. Open command prompt in windows and execute ipconfig command inside it to see your system’s IP address.
Important Note : After executing above command you’ll see many different IP address on your command prompt window, Now if you are connected to WiFi network then you need to copy/select the IPv4 address under Wireless LAN Adapter WiFi block and if you are connected to LAN then select the IPv4 address under Ethernet Adapter.
7. Start Coding for Application :
1. Open your project’s App.js file and import StyleSheet, View, TextInput, Button, Text and Alert component in your project.
1 2 3 |
import React, { Component } from 'react'; import { StyleSheet, View, TextInput, Button, Text, Alert } from 'react-native'; |
2. Create constructor() in your project and make 3 state named as UserName, UserEmail and UserPassword inside it.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
constructor() { super() this.state = { UserName: '', UserEmail: '', UserPassword: '' } } |
3. Create a function named as UserRegistrationFunction(), Inside this function we would use the fetch() API to insert data into MySQL database, As you can see we are using the URL with IP address mentioned above step with the location of PHP file. After inserting the data successfully it will print the response message coming form PHP file in Alert.
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 |
UserRegistrationFunction = () =>{ fetch('http://192.168.2.102/User_Project/user_registration.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ name: this.state.UserName, email: this.state.UserEmail, password: this.state.UserPassword }) }).then((response) => response.json()) .then((responseJson) => { // Showing response message coming from server after inserting records. Alert.alert(responseJson); }).catch((error) => { console.error(error); }); } |
4. Create 3 TextInput component and 1 Button component inside the render’s return block, Each TextInput will get a value from user and stores in State. We would call the UserRegistrationFunction() on button onPress event.
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 |
render() { return ( <View style={styles.MainContainer}> <Text style= {styles.title}>User Registration Form</Text> <TextInput placeholder="Enter User Name" onChangeText={name => this.setState({UserName : name})} underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Enter User Email" onChangeText={email => this.setState({UserEmail : email})} underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Enter User Password" onChangeText={password => this.setState({UserPassword : password})} underlineColorAndroid='transparent' style={styles.TextInputStyleClass} secureTextEntry={true} /> <Button title="Click Here To Register" onPress={this.UserRegistrationFunction} color="#2196F3" /> </View> ); } |
5. Creating Style.
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 |
const styles = StyleSheet.create({ MainContainer :{ justifyContent: 'center', flex:1, margin: 10 }, TextInputStyleClass: { textAlign: 'center', marginBottom: 7, height: 40, borderWidth: 1, borderColor: '#2196F3', borderRadius: 5 , }, title:{ fontSize: 22, color: "#009688", textAlign: 'center', marginBottom: 15 } }); |
6. 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 |
import React, { Component } from 'react'; import { StyleSheet, View, TextInput, Button, Text, Alert } from 'react-native'; export default class Project extends Component { constructor() { super() this.state = { UserName: '', UserEmail: '', UserPassword: '' } } UserRegistrationFunction = () =>{ fetch('http://192.168.2.102/User_Project/user_registration.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ name: this.state.UserName, email: this.state.UserEmail, password: this.state.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= {styles.title}>User Registration Form</Text> <TextInput placeholder="Enter User Name" onChangeText={name => this.setState({UserName : name})} underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Enter User Email" onChangeText={email => this.setState({UserEmail : email})} underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Enter User Password" onChangeText={password => this.setState({UserPassword : password})} 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, borderColor: '#2196F3', borderRadius: 5 , }, title:{ fontSize: 22, color: "#009688", textAlign: 'center', marginBottom: 15 } }); |
Screenshots :
awesome, thank you very much
Welcome 🙂 .
sir my all configuration is right but still getting network request error.
please help.
Abhishek could you test your code on online hosting server like 000webhost.
can you verify the host name in DB connection php file . I did the same mistake, In dbconfig.php I give localhost and In App.js I given network IP. If not same change it. And Postman is very helpful you can verify your connection
Thank you sir
greate tutorial
i have following error, please help me
JSON Parse error: Unexpected Identifier “Try”
Anil please check your database config file.
i’m using bitnami wampstack
it uses port 81 for start service
********************** my config file******************
***************************************
************user_registration file*********
Anil read our this tutorial : https://reactnativecode.com/connect-run-apps-using-localhost/ this would help you to configure app locally.
great
sir im having this error pls can you help JSON Parse error: Unrecognized token ‘<'
JSON Parse error: Unrecognized token ‘<'. This is my error
Please check your database config file.
hi,
my code works great on local but when i put code on 000webhost then i receive getting network request error … help me ?
Ali you need to change the your server database name and sever database password in config file and make sure when you are trying this your emulator or mobile is connected to internet .
Actually free hosting for 000webhost is not accepting external http request. All the request is blocked by their server. Try using firebase as a database.
Thanks for notifying us Sumit 🙂 .
JSON Parse error: Unrecognized token ‘<'.
and where is database config file
Sid the dbconfig.php file is our database config file.
Hi,
I want to create a registration and login app and whenever i fill registration form then all information should goes in local database and will able to login with these credentials. Please help me how can i will create this. I am stuck in this from last 10 days. My main focus local database and this database access in mobile without using internet or firebase.
Amit then you have to use Realm local database read our this tutorial this would help you : https://reactnativecode.com/realm-database-insert-update-delete-view-crud/
Hi, when i make the register it takes too much time to success on android, on ios it work really fast. I put alerts everywhere to see what was the problem and i can see that when it time of “fetch” it is when the delay happend, about 10 seconds.
do you know whats going on ?
any solution?
please help me
Regards
Cesar try this on real android device maybe it is delay because of emulator .
i try to run it using wampserver but dont get , it has occur an error ( JSON Parse error: Unrecognized token ‘<')
Junaid check the database config file and set your database username, password and database name in it.
I have same problem with (JSON Parse error: Unrecognized token ‘<')
but i make sure i have set the right database username password and database name …
I have same problem with( JSON Parse error: Unrecognized token ‘<')
I make sure i have set the right information in the config file
Stephen the code is working fine. Which URL you are using ?
while i run this code i receive this following error.
JSON Parse error: Unrecognized token ‘<'
Wahab The code is working fine i have just checked the complete code, could you tell me what modifications you have made in code.
I was able to solve the “JSON Parse error: Unrecognized token ‘<'" error…make sure you check the state name is the same E.g
name: this.state.UserName,
email: this.state.UserEmail,
password: this.state.UserPassword.
Moreover, the name , email , password must be the same as in the php page
Will can use the same fetch method for react as well rite?
Krish could you please explain me what is rite here ?
Can you wake a tutorial of user log in using php myadmin ?
Divyanshu read my this tutorial this would help you: https://reactnativecode.com/react-native-user-login-using-php-mysql/ .
Can you make a tutorial of user registration process using PostgreSQL
Thanks for your suggestion Adnan but sadly i have not tried the PostgreSQL yet. But when i learn about PostgreSQL then surely i’ll post tutorial on it.
I am trying but yet not succeeded, its hard but its not impossible.
Yesterday i did user registration process using PostgreSQL and succeeded……
Thanks for Quick reply Adnan. Can you send me your code so i could make a tutorial on it :).
Hey sir, code is run but give this alert — … — What is it ?
Rza could you tell me complete error ?
Hi, if I want to show the id in the alert box after I successfully register, what should i do in the PHP and react code? Thanks
Farah then you need to pass the id from php code to react native code and show in alert.
and how to pass the id from php code after insert? Should i add another query to select the id?
Farah where you pass the message User Registered Successfully you can pass the ID here.
Could you explain more how to pass it? I try $MSG = array (‘User Registered Successfully’, $id) and in react native is Alert.alert(responseJSON[1]), but it get error like this: [SyntaxError: JSON Parse error: Unrecognized token ‘<']
Farah did you application running correctly before making these changes ?
Hi, I am trying this currently and the application gives this same error even without making changes to the code. I also sent you an email. Could you help please?
Can we user the same method for react js as well,
If not is there any similar link
Krish you can use the same PHP files for react JS .
i am using react and using the same code to try to connect with mysql, will it work
Thanks for the reply!!
I am getting this error – any suggestions “If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.”
Krish i have no knowledge about react JS so sorry bro .
Yes, my application is running well before i change the code to send the ID
Hello! thank you for showing us this, its so useful! however it is possible to link the pop up message of ‘ User Registered Successfully’ OK button to a new page ?
Waiting for your reply!
Thank you!
Yes hanah it is possible, What actually you want please tell me ?
Hi, i am getting SyntaxError: JSON Parse error: Unrecognized token
‘<'
I have check the dbconfig file and everything else.
It also works when I directly specify the $name, $password, and $email fields in the userRegistration file.
So it seems like it is not able to get the the input from the app.
I am using Wamp server, does this affect anything?
Using your code as well url is also yours but it is not registering user. what is the problem. if i am using local host it is showing unrecognized token. i am using htdocs/web/file
and user is 192.168.54.1/web/user.php
Puneet did you change the hostname and data base host user as well as password ?
how to connect the react application with these files(.php)
Afif you have to upload these PHP files on your server and your sever should be connected with Domain name. Now after uploading these files to server you will get a URL which is your API URL.
I’m getting : Network request field but after 2 mins of submitting the info entered! and I’m using wamp server.
You are testing app locally or online ?
today I tested it online and it worked! thank you
Welcome bro 🙂 .
Hi, good tutorial, do you know if it works with genymotion? which emulator did you use?
Marcelo i am using android emulator crated using SDK Manger -> AVD Manger and i have not yet tried Genymotion.
sorry for my bad english,
thanks a lot for tutorial, great!!!
the app 100% work.
but if i release the apk, then install on my phone, and connect on same network, the app not working and nothing alert anything. why? any solution
Thanks for telling me this Ammar, I will install it in my phone and test it ASAP .
thanks for reply,
but the function is working 100% for now, i dont know why.
FYI on your posting about get data from API, the ListView not working, i try with FlatList and working.
Finally, i release the apk, and install on phone, both insert and get data 100% work, AWESOME 😉
Hi
I’m getting this error: JSON Parse error: Unexpected Identifier “Try” It happened when I signed up for the second time. While the registration process was successful for the first time and the data was sent to the database. Can you tell me where is the error?
Thank
Thank you So much 🎉 ! Great tutorial .. Each step is very clear And easy to grasp it for beginners
Thanks.. Ashwini 🙂 .