React Native User Registration With PHP MySQL Android iOS Tutorial (ok)

https://reactnativecode.com/react-native-user-registration-example-tutorial/

Ví dụ đã hoàn thành:

C:\Users\Administrator\Desktop\Apps\App.js

import React, { Component } from 'react';
import { StyleSheet, TextInput, Button, Text, View, Alert } from 'react-native';
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      UserName: '',
      UserEmail: '',
      UserPassword: ''
    };
  }
  UserRegistrationFunction = () => {
    const { UserName, UserEmail, UserPassword }     = this.state;
    fetch('http://192.168.1.100/register/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 => Alert.alert(responseJson))
    .catch(error => Alert.alert(responseJson));
  }
  render() {
    return (
      <View style={styles.MainContainer}>
        <Text style= {{ fontSize: 20, color: "#000", textAlign: "center", marginBottom: 15 }}>User Registration Form</Text>
        <TextInput placeholder="Enter User Name" onChangeText={UserName => this.setState({UserName})} underlineColorAndroid="transparent" style={styles.TextInputStyleClass} />
        <TextInput placeholder="Enter User Email" onChangeText={UserEmail => this.setState({UserEmail})} underlineColorAndroid="transparent" style={styles.TextInputStyleClass} />
        <TextInput placeholder="Enter User Password" onChangeText={UserPassword => this.setState({UserPassword})} 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,
  }
});

C:\xampp\htdocs\register\user_registration.php

<?php
include 'DBConfig.php';
$con      = mysqli_connect($HostName, $HostUser, $HostPass, $DatabaseName);
$json     = file_get_contents('php://input');
$obj      = json_decode($json, true);
$name     = $obj['name'];
$email    = $obj['email'];
$password = $obj['password'];
$CheckSQL = "SELECT * FROM UserRegistrationTable WHERE email='$email'";
$check    = mysqli_fetch_array(mysqli_query($con, $CheckSQL));
if (isset($check)) {
  $EmailExistMSG  = 'Email Already Exist, Please Try Again !!!';
  $EmailExistJson = json_encode($EmailExistMSG);
  echo $EmailExistJson;
} else {
  $Sql_Query = "insert into UserRegistrationTable (name,email,password) values ('$name','$email','$password')";
  if (mysqli_query($con, $Sql_Query)) {
    $MSG = 'User Registered Successfully';
    $jsons = json_encode($MSG);
    echo $jsons;
  } else {
  	$MSG = 'Try Again';
    $jsons = json_encode($MSG);
    echo $jsons;
  }
}
mysqli_close($con);
?>

C:\xampp\htdocs\register\DBConfig.php

<?php
	$HostName     = "localhost";
	$DatabaseName = "register";
	$HostUser     = "root";
	$HostPass     = "";
?>

C:\xampp\htdocs\register\index.php

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>Document</title>
</head>
<body>
	<script>
		var UserName = 'lionel5';
		var UserEmail = 'lionel5@gmail.com';
		var UserPassword = '123456';
		fetch('http://192.168.1.100/register/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 => console.log(responseJson))
		.catch(error => console.error(error));
	</script>
</body>
</html>

Database:

React Native User Registration With PHP MySQL Android iOS Tutorial

admin July 26, 2017React Native

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 :

123456789101112131415

<?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 :

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667

<?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.

123

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.

12345678910111213

constructor(props) { super(props) this.state = { UserName: '', UserEmail: '', UserPassword: '' } }

6. Create function named as UserRegistrationFunction() to send the Text Input data on server.

12345678910111213141516171819202122232425262728293031323334353637

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.

1234567891011121314151617181920212223242526

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.

1234567891011

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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657

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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144

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 :

Last updated

Was this helpful?