√ Tutorial Membuat CRUD React Native Data Pegawai Dengan PHP Mysql

May 20, 2019
React Native adalah sebuah Framework Mobile Javascript yang mendukung ES6++, selain mendukung Ecmascript Family, React Native juga sekarang mendukung bahasa pemrograman TypeScript.  React Native banyak dipakai oleh perusahaan besar contohnya : facebook, instagram, pinterest dan masih banyak lagi. Dengan satu kode kita bisa mengcompile ke berbagai platform khususnya Android dan iOS, bahkan react native bisa digunakan untuk desktopt windows, desktop linux, desktop mac os bahkan bisa untuk membuat website dengan react native.

Baca Juga :
Belajar Express.js Instalasi, Menampilkan Data, Routing Dan HTTP Method Request
Cara Menggambar ERD Yang Baik Dan Benar Simple!
Belajar Android MVP Design Pattern – Aplikasi Quotes Sederhana (Part I)


Ok pada kesempatan kali ini kami akan berbagi tutorial mengenai cara membuat sebuah crud dengan React Native menggunakan database Mysql dan Back End PHP.

Instalasi :


Sebelum memulai membuat aplikasi React Native pastikan kalian menginstall Node, NPM dan react native. Untuk tutorialnya dapat kalian lihat di website resminya yaitu di : https://facebook.github.io/react-native/docs/getting-started.html

Dan pilih React Native CLI Quick Start.


Membuat Projek Baru dan Install Library yang dibutuhkan:


react-native init crud_pegawai
install React Navigation Version 3.x

npm install --save react-navigation
npm install --save react-native-gesture-handler
react-native link react-native-gesture-handler 

Jika terjadi error atau kurang paham instalasi react-navigation kita bisa melihat dokumentasinya di : https://reactnavigation.org/docs/en/getting-started.html

Ok jika sudah bisa kita jalnakn lewat android atau

cd crud_pegwai 
react-native run-android atau react-native run-ios 

Maka hasilnya akan seperti di bawah ini :



Ok selamat kamu berhasil membuat aplikasi pertama react native. Ok kita lanjut untuk membuat database dan back end untuk react native kita.

Membuat Database.
Pastikan kamu suda menginstall Xampp/ Lampp/ Wampp
kemudian ke localhost/phpmyadmin dan buat databse seperti gambar di bawah ini:
Buat databse dengan nama : crud_Pegawai 
Buat tabel dengan nama : pegawai
Berikut struckture databse nya :

 


Membuat Back End PHP

 Kita akan membuat 5 file dengan nama :
1.DBConfig.php
2. DeleteStudentRecord.php
3. InsertStudentData.php
4.ShowAllStudentsList.php
5. UpdateStudentRecord.php

Taruh semu file tersebut dalam folder pegawai di dalam foler htdocs .

1.DBConfig.php

<?php

//Define your host here.
$HostName = "localhost";

//Define your database name here.
$DatabaseName = "crudrn_Pegawai";

//Define your database username here.
$HostUser = "root";

//Define your database password here.
$HostPass = "";

?>
 
 

2. DeleteStudentRecord.php

<?php

// Importing DBConfig.php file.
include 'DBConfig.php';

// Connecting to MySQL Database.
 $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 pegawai ID from JSON $obj array and store into $S_ID.
 $S_ID = $obj['pegawai_id'];

 // Creating SQL query and Updating the current record into MySQL database table.
 $Sql_Query = "DELETE FROM pegawai WHERE pegawai_id = '$S_ID'" ;


 if(mysqli_query($con,$Sql_Query)){

 // If the record inserted successfully then show the message.
$MSG = 'Record Deleted Successfully.' ;

// Converting the message into JSON format.
$json = json_encode($MSG);

// Echo the message.
 echo $json ;

 }
 else{

 echo 'Try Again';

 }
 mysqli_close($con);
?>



3.InsertStudentData.php

<?php

// Importing DBConfig.php file.
include 'DBConfig.php';

// Connecting to MySQL Database.
 $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);

 $S_Name = $obj['pegawai_nama'];

 // Populate pegawai from JSON $obj array and store into $S_Class.
 $S_Class = $obj['pegawai_gaji'];


 // Creating SQL query and insert the record into MySQL database table.
 $Sql_Query = "insert into pegawai (pegawai_nama ,pegawai_gaji ) values ('$S_Name','$S_Class')";


 if(mysqli_query($con,$Sql_Query)){

 // If the record inserted successfully then show the message.
$MSG = 'Record Successfully Inserted 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);
?>

4. ShowAllStudentsList.php
<?php
include 'DBConfig.php';

// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

if ($conn->connect_error) {

 die("Connection failed: " . $conn->connect_error);
}

// Creating SQL command to fetch all records from Table.
$sql = "SELECT * FROM pegawai";

$result = $conn->query($sql);

if ($result->num_rows >0) {


 while($row[] = $result->fetch_assoc()) {

 $item = $row;

 $json = json_encode($item);

 }

} else {
 echo "No Results Found.";
}
 echo $json;
$conn->close();
?> 

 5. UpdateStudentRecord.php

<?php

// Importing DBConfig.php file.
include 'DBConfig.php';

// Connecting to MySQL Database.
 $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 pegawai ID from JSON $obj array and store into $S_Name.
 $S_ID = $obj['pegawai_id'];

 // Populate pegawai name from JSON $obj array and store into $S_Name.
 $S_Nama = $obj['pegawai_nama'];

 // Populate pegawai from JSON $obj array and store into $S_Class.
 $S_Gaji = $obj['pegawai_gaji'];


 // Creating SQL query and insert the record into MySQL database table.
 $Sql_Query = "UPDATE pegawai SET pegawai_nama= '$S_Nama', pegawai_gaji = '$S_Gaji' WHERE pegawai_id = $S_ID";

 if(mysqli_query($con,$Sql_Query)){

 // If the record inserted successfully then show the message.
$MSG = 'Record Successfully Inserted 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);
?>


Menulis Kode React Native 

Disini kita akan mengedit satu file App.js dan membuat 3 buah file baru :

1.PegawaiMain.js
2.PegawaiRead.js
3.PegawaiEdit.js

App.js:

import React from 'react';
import { createAppContainer, createStackNavigator } from 'react-navigation';
import PegawaiMain from './src/pegawai/PegawaiMain';
import PegawaiRead from './src/pegawai/PegawaiRead';
import PegawaiEdit from './src/pegawai/PegawaiEdit';



const RootStack = createStackNavigator(
  {

    PegawaiEdit: {
      screen: PegawaiEdit,
      navigationOptions: {

      }
    },   
    PegawaiMain: {
      screen: PegawaiMain,
      navigationOptions: {

      }
    },

    PegawaiRead: {
      screen: PegawaiRead,
      navigationOptions: {

      }
    },
   
  },
  {
    initialRouteName: 'PegawaiMain', // ini root
  }
);

const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {

  render() {
    return <AppContainer />;
  }
}

 

PegawaiMain.js:

import React, { Component } from "react";

import {
  StyleSheet,
  View,
  Alert,
  TextInput,
  Text,
  Platform,
  TouchableOpacity,
} from "react-native";


export default class MainActivity extends Component {
  static navigationOptions = {
    title: "Pegawai Data"
  };

  constructor(props) {
    super(props);
    this.state = {
      TextInput_Student_Name: "",
      TextInput_Student_Class: ""
    };
  }

  InsertStudentRecordsToServer = () => {
    fetch("http://192.168.43.131/pegawai/InsertStudentData.php", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        pegawai_nama: this.state.TextInput_Student_Name,

        pegawai_gaji: this.state.TextInput_Student_Class,

 
      })
    })
      .then(response => response.json())
      .then(responseJson => {
        // Showing response message coming from server after inserting records.
        Alert.alert(responseJson);
      })
      .catch(error => {
        console.error(error);
      });
  };

  GoTo_Show_StudentList_Activity_Function = () => {
    this.props.navigation.navigate("PegawaiRead");
  };

  render() {
    return (
      <View style={styles.MainContainer}>
        <Text style={{ fontSize: 20, textAlign: "center", marginBottom: 7 }}>
          {" "}
          Pendaftaran Data Pegawai{" "}
        </Text>

        <TextInput
          placeholder="Data Nama"
          onChangeText={TextInputValue =>
            this.setState({ TextInput_Student_Name: TextInputValue })
          }
          underlineColorAndroid="transparent"
          style={styles.TextInputStyleClass}
        />

        <TextInput
          placeholder="Data Gaji"
          onChangeText={TextInputValue =>
            this.setState({ TextInput_Student_Class: TextInputValue })
          }
          underlineColorAndroid="transparent"
          style={styles.TextInputStyleClass}
        />


        <TouchableOpacity
          activeOpacity={0.4}
          style={styles.TouchableOpacityStyle}
          onPress={this.InsertStudentRecordsToServer}
        >
          <Text style={styles.TextStyle}>
            {" "}
            TAMBAHKAN DATA PEGAWAI{" "}
          </Text>
        </TouchableOpacity>

        <TouchableOpacity
          activeOpacity={0.4}
          style={styles.TouchableOpacityStyle}
          onPress={this.GoTo_Show_StudentList_Activity_Function}
        >
          <Text style={styles.TextStyle}>
            {" "}
            TAMPILKAN SELURUH DATA KARYAWAN{" "}
          </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    alignItems: "center",
    flex: 1,
    paddingTop: 30,
    backgroundColor: "#fff"
  },

  MainContainer_For_Show_StudentList_Activity: {
    flex: 1,
    paddingTop: Platform.OS == "ios" ? 20 : 0,
    marginLeft: 5,
    marginRight: 5
  },

  TextInputStyleClass: {
    textAlign: "center",
    width: "90%",
    marginBottom: 7,
    height: 40,
    borderWidth: 1,
    borderColor: "#30cb63",
    borderRadius: 5
  },

  TouchableOpacityStyle: {
    paddingTop: 10,
    paddingBottom: 10,
    borderRadius: 5,
    marginBottom: 7,
    width: "90%",
    backgroundColor: "#30cb63"
  },

  TextStyle: {
    color: "#fff",
    textAlign: "center"
  },

  rowViewContainer: {
    fontSize: 20,
    paddingRight: 10,
    paddingTop: 10,
    paddingBottom: 10
  }
});

 

PegawaiRead.js:

import React, { Component } from "react";

import {
  StyleSheet,
  View,
  Alert,
  TextInput,
  Button,
  Text,
  Platform,
  TouchableOpacity,
  ListView,
  ActivityIndicator
} from "react-native";

export default class PegawaiRead extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoading: true
    };
  }

  static navigationOptions = {
    title: "Daftar Pegawai"
  };

  componentDidMount() {
    return fetch("http://192.168.43.131/pegawai/ShowAllStudentsList.php")
      .then(response => response.json())
      .then(responseJson => {
        let ds = new ListView.DataSource({
          rowHasChanged: (r1, r2) => r1 !== r2
        });
        this.setState(
          {
            isLoading: false,
            dataSource: ds.cloneWithRows(responseJson)
          },
          function() {
            // In this block you can do something with new state.
          }
        );
      })
      .catch(error => {
        console.error(error);
      });
  }

  GetStudentIDFunction = (
    pegawai_id,
    pegawai_nama,
    pegawai_gaji
  ) => {
    this.props.navigation.navigate("PegawaiEdit", {
      ID: pegawai_id,
      NAMA: pegawai_nama,
      GAJI: pegawai_gaji,
    });
  };

  ListViewItemSeparator = () => {
    return (
      <View
        style={{
          height: 0.5,
          width: "100%",
          backgroundColor: "#000"
        }}
      />
    );
  };

  render() {
    if (this.state.isLoading) {
      return (
        <View style={{ flex: 1, paddingTop: 20 }}>
          <ActivityIndicator />
        </View>
      );
    }

    return (
      <View style={styles.MainContainer_For_Show_StudentList_Activity}>
        <ListView
          dataSource={this.state.dataSource}
          renderSeparator={this.ListViewItemSeparator}
          renderRow={rowData => (
            <Text
              style={styles.rowViewContainer}
              onPress={this.GetStudentIDFunction.bind(
                this,
                rowData.pegawai_id,
                rowData.pegawai_nama,
                rowData.pegawai_gaji,
              )}
            >
              {rowData.pegawai_nama}
            </Text>
          )}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    alignItems: "center",
    flex: 1,
    paddingTop: 30,
    backgroundColor: "#fff"
  },

  MainContainer_For_Show_StudentList_Activity: {
    flex: 1,
    paddingTop: Platform.OS == "ios" ? 20 : 0,
    marginLeft: 5,
    marginRight: 5
  },

  TextInputStyleClass: {
    textAlign: "center",
    width: "90%",
    marginBottom: 7,
    height: 40,
    borderWidth: 1,
    borderColor: "#30cb63",
    borderRadius: 5
  },

  TouchableOpacityStyle: {
    paddingTop: 10,
    paddingBottom: 10,
    borderRadius: 5,
    marginBottom: 7,
    width: "90%",
    backgroundColor: "#30cb63"
  },

  TextStyle: {
    color: "#fff",
    textAlign: "center"
  },

  rowViewContainer: {
    fontSize: 20,
    paddingRight: 10,
    paddingTop: 10,
    paddingBottom: 10
  }
});

PegawaiEdit.js:

import React, { Component } from "react";

import {
  StyleSheet,
  View,
  Alert,
  TextInput,
  Button,
  Text,
  Platform,
  TouchableOpacity,
  ListView,
  ActivityIndicator
} from "react-native";

export default class PegawaiEdit extends Component {
  constructor(props) {
    super(props);

    this.state = {
      TextInput_ID: "",
      TextInput_Nama: "",
      TextInput_Gaji: "",

    };
  }

  componentDidMount() {
    // Received Student Details Sent From Previous Activity and Set Into State.
    this.setState({
      TextInput_ID: this.props.navigation.state.params.ID,
      TextInput_Nama: this.props.navigation.state.params.NAMA,
      TextInput_Gaji: this.props.navigation.state.params.GAJI,
    });
  }

  static navigationOptions = {
    title: "EditStudentRecordActivity"
  };

  UpdateStudentRecord = () => {
    fetch("http://192.168.43.131/pegawai/UpdateStudentRecord.php", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        pegawai_id: this.state.TextInput_ID,
        pegawai_nama: this.state.TextInput_Nama,
        pegawai_gaji: this.state.TextInput_Gaji,
      })
    })
      .then(response => response.json())
      .then(responseJson => {
        // Showing response message coming from server updating records.
        Alert.alert(responseJson);
      })
      .catch(error => {
        console.error(error);
      });
  };

  DeleteStudentRecord = () => {
    fetch("http://192.168.43.131/pegawai/DeleteStudentRecord.php", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        student_id: this.state.TextInput_ID
      })
    })
      .then(response => response.json())
      .then(responseJson => {
        // Showing response message coming from server after inserting records.
        Alert.alert(responseJson);
      })
      .catch(error => {
        console.error(error);
      });

    this.props.navigation.navigate("PegawaiMain");
  };

  render() {
    return (
      <View style={styles.MainContainer}>
        <Text style={{ fontSize: 20, textAlign: "center", marginBottom: 7 }}>
          {" "}
          Edit Student Record Form{" "}
        </Text>

        <TextInput
          placeholder="Nama Pegawai"
          value={this.state.TextInput_Nama}
          onChangeText={TextInputValue =>
            this.setState({ TextInput_Nama: TextInputValue })
          }
          underlineColorAndroid="transparent"
          style={styles.TextInputStyleClass}
        />

        <TextInput
          placeholder="Gaji Karyawan"
          value={this.state.TextInput_Gaji}
          onChangeText={TextInputValue =>
            this.setState({ TextInput_Gaji: TextInputValue })
          }
          underlineColorAndroid="transparent"
          style={styles.TextInputStyleClass}
        />


        <TouchableOpacity
          activeOpacity={0.4}
          style={styles.TouchableOpacityStyle}
          onPress={this.UpdateStudentRecord}
        >
          <Text style={styles.TextStyle}> UPDATE DATA PEGWAI </Text>
        </TouchableOpacity>

        <TouchableOpacity
          activeOpacity={0.4}
          style={styles.TouchableOpacityStyle}
          onPress={this.DeleteStudentRecord}
        >
          <Text style={styles.TextStyle}> DELETE DATA PEGAWAI </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  MainContainer: {
    alignItems: "center",
    flex: 1,
    paddingTop: 30,
    backgroundColor: "#fff"
  },

  MainContainer_For_Show_StudentList_Activity: {
    flex: 1,
    paddingTop: Platform.OS == "ios" ? 20 : 0,
    marginLeft: 5,
    marginRight: 5
  },

  TextInputStyleClass: {
    textAlign: "center",
    width: "90%",
    marginBottom: 7,
    height: 40,
    borderWidth: 1,
    borderColor: "#30cb63",
    borderRadius: 5
  },

  TouchableOpacityStyle: {
    paddingTop: 10,
    paddingBottom: 10,
    borderRadius: 5,
    marginBottom: 7,
    width: "90%",
    backgroundColor: "#30cb63"
  },

  TextStyle: {
    color: "#fff",
    textAlign: "center"
  },

  rowViewContainer: {
    fontSize: 20,
    paddingRight: 10,
    paddingTop: 10,
    paddingBottom: 10
  }
});



Maka hasil dari keseluruhan kode di atas akan seperti ini jika kita menjalankan perintah : rect-native run-android atau react-native run-ios:




 

 Ok sekian terimakasih semoga dapat bermanfaat untuk kodingan + server + sql dapat di clone di github saya, jangan lupa folllow dan kasih stars.

Github Me



 

Artikel Terkait

Next Article
« Prev Post
Previous Article
Next Post »
Penulisan markup di komentar
  • Untuk menulis huruf bold gunakan <strong></strong> atau <b></b>.
  • Untuk menulis huruf italic gunakan <em></em> atau <i></i>.
  • Untuk menulis huruf underline gunakan <u></u>.
  • Untuk menulis huruf strikethrought gunakan <strike></strike>.
  • Untuk menulis kode HTML gunakan <code></code> atau <pre></pre> atau <pre><code></code></pre>, dan silakan parse kode pada kotak parser di bawah ini.

Disqus
Tambahkan komentar Anda