This tutorial is the fully advanced tutorial in react native because in this tutorial we would going to implement CRUD operations in react native android iOS applications. CRUD operations consist four type of major functions Add, Edit(Modify), Delete and View. So we would going to create a react native app with Insert Update Display Delete CRUD Operations From MySQL database using PHP.
What we are doing in this project :
We are creating a react native app with react-navigation library because without the react-navigation we cannot add multiple activities in our project. Now would insert student records in online MySQL database using PHP from our react native application. After that we would retrieve all those records into ListView in next activity. Now we would open the selected record into next activity and automatically fill each data into TextInput. We would also gives the option to delete the current selected data. So let’s get started 🙂 .
Project Description File Structure:
PHP Files in this project :
- DBConfig.php
- InsertStudentData.php
- ShowAllStudentsList.php
- UpdateStudentRecord.php
- DeleteStudentRecord.php
Activity classes in this project created in App.js file
- MainActivity
- ShowStudentListActivity
- EditStudentRecordActivity
Contents in this project Insert Update Display Delete CRUD Operations From MySQL DB in react native using PHP :
1. Create a fresh MySQL database in your online hosting server.
2. Create a Table named as StudentDetailsTable with 5 columns student_id, student_name, student_class, student_phone_number and student_email. Now we would make the student_id as Primary key with Auto Increment. See the below screenshot for more details. This would be our main table and we would perform all CRUD operations on this table from our MySQL database.
We would make 5 PHP files named as DBConfig.php , InsertStudentData.php , ShowAllStudentsList.php , UpdateStudentRecord.php and DeleteStudentRecord.php . You need to upload all these files to your hosting server.
- DBConfig.php : This file consist all the MySQL database connection configuration like MySQL database host name, MySQL database name, MySQL database username, MySQL database password.
- InsertStudentData.php : This file would receive the sent data from react native app and insert that data into MySQL table.
- ShowAllStudentsList.php : This file would convert all the existing present MySQL database data into JSON format.
- UpdateStudentRecord.php : This file would update the existing opened record in app.
- DeleteStudentRecord.php : This file would delete the existing open record in react native app.
1. Code for DBConfig.php.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"; ?> |
2. Code for InsertStudentData.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 |
<?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 Student name from JSON $obj array and store into $S_Name. $S_Name = $obj['student_name']; // Populate Student Class from JSON $obj array and store into $S_Class. $S_Class = $obj['student_class']; // Populate Student Phone Number from JSON $obj array and store into $S_Phone_Number. $S_Phone_Number = $obj['student_phone_number']; // Populate Email from JSON $obj array and store into $S_Email. $S_Email = $obj['student_email']; // Creating SQL query and insert the record into MySQL database table. $Sql_Query = "insert into StudentDetailsTable (student_name,student_class,student_phone_number,student_email) values ('$S_Name','$S_Class','$S_Phone_Number','$S_Email')"; 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); ?> |
3. Code for ShowAllStudentsList.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 |
<?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 StudentDetailsTable"; $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(); ?> |
4. Code for UpdateStudentRecord.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 |
<?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 Student ID from JSON $obj array and store into $S_Name. $S_ID = $obj['student_id']; // Populate Student name from JSON $obj array and store into $S_Name. $S_Name = $obj['student_name']; // Populate Student Class from JSON $obj array and store into $S_Class. $S_Class = $obj['student_class']; // Populate Student Phone Number from JSON $obj array and store into $S_Phone_Number. $S_Phone_Number = $obj['student_phone_number']; // Populate Email from JSON $obj array and store into $S_Email. $S_Email = $obj['student_email']; // Creating SQL query and insert the record into MySQL database table. $Sql_Query = "UPDATE StudentDetailsTable SET student_name= '$S_Name', student_class = '$S_Class', student_phone_number = '$S_Phone_Number', student_email = '$S_Email' WHERE student_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); ?> |
5. Code for DeleteStudentRecord.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 |
<?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 Student ID from JSON $obj array and store into $S_ID. $S_ID = $obj['student_id']; // Creating SQL query and Updating the current record into MySQL database table. $Sql_Query = "DELETE FROM StudentDetailsTable WHERE student_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); ?> |
4. Start a new react native project or open your existing project’s App.js file.
5. Open your project’s folder in Command Prompt / Terminal and install react-navigation library. by typing npm install --save react-navigation command. You can read my this tutorial to understand how activity structure would works.
6. Import StyleSheet, View, Alert, TextInput, Button, Text, Platform, TouchableOpacity, ListView and ActivityIndicator component in your project.
1 2 3 |
import React, { Component } from 'react'; import { StyleSheet, View, Alert, TextInput, Button, Text, Platform, TouchableOpacity, ListView, ActivityIndicator } from 'react-native'; |
7. Import StackNavigator from react-navigation library.
1 |
import { StackNavigator } from 'react-navigation'; |
8. Create a class named as MainActivity in your project. This would be your first screen of app with User registration from.
navigationOptions : Used to set the Activity title which display inside the Action Title bar.
constructor() : Creating 4 States inside the constructor() named as TextInput_Student_Name, TextInput_Student_Class, TextInput_Student_PhoneNumber, TextInput_Student_Email . Each state is used to hold the entered value from TextInput.
InsertStudentRecordsToServer() : This function would run the react native’s fetch() web api and send the all TextInput entered value to server and after successfully insertion it will show the response message coming from server into Alert dialog box.
GoTo_Show_StudentList_Activity_Function() : In this function we would open the ShowStudentListActivity represent as Second activity.
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 |
class MainActivity extends Component { static navigationOptions = { title: 'MainActivity', }; constructor(props) { super(props) this.state = { TextInput_Student_Name: '', TextInput_Student_Class: '', TextInput_Student_PhoneNumber: '', TextInput_Student_Email: '', } } InsertStudentRecordsToServer = () =>{ fetch('https://reactnativecode.000webhostapp.com/Student/InsertStudentData.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ student_name : this.state.TextInput_Student_Name, student_class : this.state.TextInput_Student_Class, student_phone_number : this.state.TextInput_Student_PhoneNumber, student_email: this.state.TextInput_Student_Email }) }).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('Second'); } render() { return ( <View style={styles.MainContainer}> <Text style={{fontSize: 20, textAlign: 'center', marginBottom: 7}}> Student Registration Form </Text> <TextInput placeholder="Enter Student Name" onChangeText={ TextInputValue => this.setState({ TextInput_Student_Name : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Enter Student Class" onChangeText={ TextInputValue => this.setState({ TextInput_Student_Class : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Enter Student Phone Number" onChangeText={ TextInputValue => this.setState({ TextInput_Student_PhoneNumber : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Enter Student Email" onChangeText={ TextInputValue => this.setState({ TextInput_Student_Email : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TouchableOpacity activeOpacity = { .4 } style={styles.TouchableOpacityStyle} onPress={this.InsertStudentRecordsToServer} > <Text style={styles.TextStyle}> INSERT STUDENT RECORD TO SERVER </Text> </TouchableOpacity> <TouchableOpacity activeOpacity = { .4 } style={styles.TouchableOpacityStyle} onPress={this.GoTo_Show_StudentList_Activity_Function} > <Text style={styles.TextStyle}> SHOW ALL INSERTED STUDENT RECORDS IN LISTVIEW </Text> </TouchableOpacity> </View> ); } } |
Screenshot of MainActivity :
9. Create class named as ShowStudentListActivity. This class would display all the entered students records in ListView.
constructor() : We are creating a Boolean type State named as isLoading. This state is used to show and hide the ActivityIndicator after done loading JSON data into ListView. If the isLoading value is true then it will show the ActivityIndicator and if the isLoading value is false then it will hide the ActivityIndicator.
navigationOptions : Used to set the Activity Title shows inside the Title Action bar.
componentDidMount() : This is a inbuilt function of React Native. This function would automatically calls on activity start up time. We would write the Fetch() Web code inside componentDidMount() method so when the this activity opens then it will start a web call and fetch the JSON data from server and display inside ListView. We are only displaying Student Names inside this ListView.
GetStudentIDFunction() : This function is very important for this class because in this function we would send the student_id, student_name, student_class, student_phone_number and student_email address to next EditStudentRecordActivity on ListView item onPress event. When use clicks on any ListView item then it will automatically get all the values form current selected record and navigate to next activity where it will be automatically received and filled into TextInput.
ListViewItemSeparator() : This function would render a separator line between each item of ListView.
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 |
class ShowStudentListActivity extends Component { constructor(props) { super(props); this.state = { isLoading: true } } static navigationOptions = { title: 'ShowStudentListActivity', }; componentDidMount() { return fetch('https://reactnativecode.000webhostapp.com/Student/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=(student_id,student_name, student_class, student_phone_number, student_email)=>{ this.props.navigation.navigate('Third', { ID : student_id, NAME : student_name, CLASS : student_class, PHONE_NUMBER : student_phone_number, EMAIL : student_email }); } ListViewItemSeparator = () => { return ( <View style={{ height: .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.student_id, rowData.student_name, rowData.student_class, rowData.student_phone_number, rowData.student_email )} > {rowData.student_name} </Text> } /> </View> ); } } |
Screenshot of ShowStudentListActivity :
10. Create a class named as EditStudentRecordActivity. This class is used to Edit the current open record to MySQL database. This class is also used to delete the current selected opened record.
constructor : We would create 5 state named as TextInput_Student_ID, TextInput_Student_Name, TextInput_Student_Class, TextInput_Student_PhoneNumber, TextInput_Student_Email in constructor(). Each state is used to store and hold the already sent data from previous activity.
componentDidMount() : Storing all the sent value from previous activity into State using this.props.navigation.state.params .
navigationOptions : Setting up the activity title shows inside the Title Action bar.
UpdateStudentRecord() : This function would get the all TextInput entered value and send them to server using fetch() API where they will update the existing record using ID.
DeleteStudentRecord() : This function would get the only Student ID from TextInput_Student_ID and send the only TextInput_Student_ID to server . On server we would delete the current record according to ID.
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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 |
class EditStudentRecordActivity extends Component { constructor(props) { super(props) this.state = { TextInput_Student_ID: '', TextInput_Student_Name: '', TextInput_Student_Class: '', TextInput_Student_PhoneNumber: '', TextInput_Student_Email: '', } } componentDidMount(){ // Received Student Details Sent From Previous Activity and Set Into State. this.setState({ TextInput_Student_ID : this.props.navigation.state.params.ID, TextInput_Student_Name: this.props.navigation.state.params.NAME, TextInput_Student_Class: this.props.navigation.state.params.CLASS, TextInput_Student_PhoneNumber: this.props.navigation.state.params.PHONE_NUMBER, TextInput_Student_Email: this.props.navigation.state.params.EMAIL, }) } static navigationOptions = { title: 'EditStudentRecordActivity', }; UpdateStudentRecord = () =>{ fetch('https://reactnativecode.000webhostapp.com/Student/UpdateStudentRecord.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ student_id : this.state.TextInput_Student_ID, student_name : this.state.TextInput_Student_Name, student_class : this.state.TextInput_Student_Class, student_phone_number : this.state.TextInput_Student_PhoneNumber, student_email: this.state.TextInput_Student_Email }) }).then((response) => response.json()) .then((responseJson) => { // Showing response message coming from server updating records. Alert.alert(responseJson); }).catch((error) => { console.error(error); }); } DeleteStudentRecord = () =>{ fetch('https://reactnativecode.000webhostapp.com/Student/DeleteStudentRecord.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ student_id : this.state.TextInput_Student_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('First'); } render() { return ( <View style={styles.MainContainer}> <Text style={{fontSize: 20, textAlign: 'center', marginBottom: 7}}> Edit Student Record Form </Text> <TextInput placeholder="Student Name Shows Here" value={this.state.TextInput_Student_Name} onChangeText={ TextInputValue => this.setState({ TextInput_Student_Name : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Student Class Shows Here" value={this.state.TextInput_Student_Class} onChangeText={ TextInputValue => this.setState({ TextInput_Student_Class : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Student Phone Number Shows Here" value={this.state.TextInput_Student_PhoneNumber} onChangeText={ TextInputValue => this.setState({ TextInput_Student_PhoneNumber : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Student Email Shows Here" value={this.state.TextInput_Student_Email} onChangeText={ TextInputValue => this.setState({ TextInput_Student_Email : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TouchableOpacity activeOpacity = { .4 } style={styles.TouchableOpacityStyle} onPress={this.UpdateStudentRecord} > <Text style={styles.TextStyle}> UPDATE STUDENT RECORD </Text> </TouchableOpacity> <TouchableOpacity activeOpacity = { .4 } style={styles.TouchableOpacityStyle} onPress={this.DeleteStudentRecord} > <Text style={styles.TextStyle}> DELETE CURRENT RECORD </Text> </TouchableOpacity> </View> ); } } |
11. Create StackNavigator and define all your activity classes inside it.
1 2 3 4 5 6 7 8 9 10 11 |
export default MyNewProject = StackNavigator( { First: { screen: MainActivity }, Second: { screen: ShowStudentListActivity }, Third: { screen: EditStudentRecordActivity } }); |
12. Create CSS Style classes for All activities.
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 |
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: '#FF5722', borderRadius: 5 , }, TouchableOpacityStyle: { paddingTop:10, paddingBottom:10, borderRadius:5, marginBottom:7, width: '90%', backgroundColor: '#00BCD4' }, TextStyle:{ color:'#fff', textAlign:'center', }, rowViewContainer: { fontSize: 20, paddingRight: 10, paddingTop: 10, paddingBottom: 10, } }); |
13. 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 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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 |
import React, { Component } from 'react'; import { StyleSheet, View, Alert, TextInput, Button, Text, Platform, TouchableOpacity, ListView, ActivityIndicator } from 'react-native'; import { StackNavigator } from 'react-navigation'; class MainActivity extends Component { static navigationOptions = { title: 'MainActivity', }; constructor(props) { super(props) this.state = { TextInput_Student_Name: '', TextInput_Student_Class: '', TextInput_Student_PhoneNumber: '', TextInput_Student_Email: '', } } InsertStudentRecordsToServer = () =>{ fetch('https://reactnativecode.000webhostapp.com/Student/InsertStudentData.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ student_name : this.state.TextInput_Student_Name, student_class : this.state.TextInput_Student_Class, student_phone_number : this.state.TextInput_Student_PhoneNumber, student_email: this.state.TextInput_Student_Email }) }).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('Second'); } render() { return ( <View style={styles.MainContainer}> <Text style={{fontSize: 20, textAlign: 'center', marginBottom: 7}}> Student Registration Form </Text> <TextInput placeholder="Enter Student Name" onChangeText={ TextInputValue => this.setState({ TextInput_Student_Name : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Enter Student Class" onChangeText={ TextInputValue => this.setState({ TextInput_Student_Class : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Enter Student Phone Number" onChangeText={ TextInputValue => this.setState({ TextInput_Student_PhoneNumber : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Enter Student Email" onChangeText={ TextInputValue => this.setState({ TextInput_Student_Email : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TouchableOpacity activeOpacity = { .4 } style={styles.TouchableOpacityStyle} onPress={this.InsertStudentRecordsToServer} > <Text style={styles.TextStyle}> INSERT STUDENT RECORD TO SERVER </Text> </TouchableOpacity> <TouchableOpacity activeOpacity = { .4 } style={styles.TouchableOpacityStyle} onPress={this.GoTo_Show_StudentList_Activity_Function} > <Text style={styles.TextStyle}> SHOW ALL INSERTED STUDENT RECORDS IN LISTVIEW </Text> </TouchableOpacity> </View> ); } } class ShowStudentListActivity extends Component { constructor(props) { super(props); this.state = { isLoading: true } } static navigationOptions = { title: 'ShowStudentListActivity', }; componentDidMount() { return fetch('https://reactnativecode.000webhostapp.com/Student/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=(student_id,student_name, student_class, student_phone_number, student_email)=>{ this.props.navigation.navigate('Third', { ID : student_id, NAME : student_name, CLASS : student_class, PHONE_NUMBER : student_phone_number, EMAIL : student_email }); } ListViewItemSeparator = () => { return ( <View style={{ height: .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.student_id, rowData.student_name, rowData.student_class, rowData.student_phone_number, rowData.student_email )} > {rowData.student_name} </Text> } /> </View> ); } } class EditStudentRecordActivity extends Component { constructor(props) { super(props) this.state = { TextInput_Student_ID: '', TextInput_Student_Name: '', TextInput_Student_Class: '', TextInput_Student_PhoneNumber: '', TextInput_Student_Email: '', } } componentDidMount(){ // Received Student Details Sent From Previous Activity and Set Into State. this.setState({ TextInput_Student_ID : this.props.navigation.state.params.ID, TextInput_Student_Name: this.props.navigation.state.params.NAME, TextInput_Student_Class: this.props.navigation.state.params.CLASS, TextInput_Student_PhoneNumber: this.props.navigation.state.params.PHONE_NUMBER, TextInput_Student_Email: this.props.navigation.state.params.EMAIL, }) } static navigationOptions = { title: 'EditStudentRecordActivity', }; UpdateStudentRecord = () =>{ fetch('https://reactnativecode.000webhostapp.com/Student/UpdateStudentRecord.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ student_id : this.state.TextInput_Student_ID, student_name : this.state.TextInput_Student_Name, student_class : this.state.TextInput_Student_Class, student_phone_number : this.state.TextInput_Student_PhoneNumber, student_email: this.state.TextInput_Student_Email }) }).then((response) => response.json()) .then((responseJson) => { // Showing response message coming from server updating records. Alert.alert(responseJson); }).catch((error) => { console.error(error); }); } DeleteStudentRecord = () =>{ fetch('https://reactnativecode.000webhostapp.com/Student/DeleteStudentRecord.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ student_id : this.state.TextInput_Student_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('First'); } render() { return ( <View style={styles.MainContainer}> <Text style={{fontSize: 20, textAlign: 'center', marginBottom: 7}}> Edit Student Record Form </Text> <TextInput placeholder="Student Name Shows Here" value={this.state.TextInput_Student_Name} onChangeText={ TextInputValue => this.setState({ TextInput_Student_Name : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Student Class Shows Here" value={this.state.TextInput_Student_Class} onChangeText={ TextInputValue => this.setState({ TextInput_Student_Class : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Student Phone Number Shows Here" value={this.state.TextInput_Student_PhoneNumber} onChangeText={ TextInputValue => this.setState({ TextInput_Student_PhoneNumber : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TextInput placeholder="Student Email Shows Here" value={this.state.TextInput_Student_Email} onChangeText={ TextInputValue => this.setState({ TextInput_Student_Email : TextInputValue }) } underlineColorAndroid='transparent' style={styles.TextInputStyleClass} /> <TouchableOpacity activeOpacity = { .4 } style={styles.TouchableOpacityStyle} onPress={this.UpdateStudentRecord} > <Text style={styles.TextStyle}> UPDATE STUDENT RECORD </Text> </TouchableOpacity> <TouchableOpacity activeOpacity = { .4 } style={styles.TouchableOpacityStyle} onPress={this.DeleteStudentRecord} > <Text style={styles.TextStyle}> DELETE CURRENT RECORD </Text> </TouchableOpacity> </View> ); } } export default MyNewProject = StackNavigator( { First: { screen: MainActivity }, Second: { screen: ShowStudentListActivity }, Third: { screen: EditStudentRecordActivity } }); 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: '#FF5722', borderRadius: 5 , }, TouchableOpacityStyle: { paddingTop:10, paddingBottom:10, borderRadius:5, marginBottom:7, width: '90%', backgroundColor: '#00BCD4' }, TextStyle:{ color:'#fff', textAlign:'center', }, rowViewContainer: { fontSize: 20, paddingRight: 10, paddingTop: 10, paddingBottom: 10, } }); |
Screenshot in Android device :
Aweome tutorial, i was waiting for it for a very long time 🙂
Welcome Bro 🙂 .
code will Works on expo projects?
Is there any tutorial that can do the same thing like this for Firebase?
No Winson i have not created tutorial on Firebase but soon i will publish new tutorial on Firebase 🙂 .
Could you make a video?
Video on which topic ?
yes please make tutorial CRUD video with mysql database
Andre you want to upload a demo video of the app ? Am i correct .
i mean can u make crud video like
– how to upload video to mysql database
– how to show video in listview from mysql database
– how to update and delete video from mysql database
🙂 🙂 🙂
Sure Andre we will soon tutorials regarding to your query 🙂 .
please do a tutorial on image upload to php server mysql
Yes, soon we will 🙂 .
great tutorial,
How to create API using login and Creat , Update, Delete record by each username
Thank you
How to create API login and Create, Update, Delete, SHow record by each username using php. please advice
Read our this tutorial this would help you : https://reactnativecode.com/click-filter-json-selected-listview-data-android-ios/
Awesome!!!
Thank you very much Admin.
Welcome Neo 🙂 .
Hi Admin, You are doing a great Job. This Tutorial is Very well explained.
please help me, How to Connect my React native app to local host xampp & Mysql DB.
I would like to perform CRUD operations on my local host, I am using xampp with Mysql….
Usmaan i will post a new tutorial regarding connecting react native app to localhost soon 🙂 .
Thanks Admin, we will be waiting…….
I have posted the tutorial here is the link https://reactnativecode.com/connect-run-apps-using-localhost/
Great Tutorial Admin…..Not even a single error in your code…Hats off Brother…..
Welcome bro 🙂 .
Hi, Sr.
I’ve tried to use your URL and DB’s config in my Host but does’t works.
I just upload all the PHP files in my MySQL and I changed the fetch URL to mine, like this : fetch(‘https://appdejore.000webhostapp.com/ShowAllStudentsList.php’ , etc…
It works at web, but when I run in my React Native, doesn’t. A red error appears…
Can i have some help? My host is :
//Define your host here.
$HostName = “localhost”;
//Define your database name here.
$DatabaseName = “id6607105_app_teste”;
//Define your database username here.
$HostUser = “id6607105_app”;
//Define your database password here.
$HostPass = “123456789”;
Login: [email protected]
Password: 1234
Lucas check if their hostname is something different.
What version of the react is used in this project?
0.55 is the version of this project IGOR , why ?
Hi admin,
For xamp above code works Fine…
Now i am using online server to for this tutorials.
what will be the host name, username,host pass…. for Online server.
Also, how to upload files on online server pls explain in detail…
thanks
Usmaan you will find the host name and host pass and host username and database name on your hosting provider control panel.
Thanks admin,
Iam able to insert data in database BuT show all inserted students recordin list view button is going to next screen..
showstudent list activity is not working, i can see just 3 lines……(i have inserted 3 student names)
Admin Bro,
Can we use similar method of “fetch”….
[return fetch(‘https://reactnativecode.000webhostapp.com/Student/ShowAllStudentsList.php’)…………] in a production App.
OR Do i need to create API…….
Please Answer asap..
Thanks.
Yes Usmaan you can use this method .
Admin Bro,
Thanks for the reply….
1.How to make the search functionality for this students database.
2. Will there be any security issues or functionality issues in App, If we don’t create END POINTS or API please Guide…….
3. I am planning to built a e-commerce App, Which is the best way; Creating endpoint & API or Without API as you have used in this Tutorial of Student Data….
Thanks.
hello Usmaan,
1. You can use our https://reactnativecode.com/add-search-bar-filter/ tutorial for search functionality.
2. No usmaan there is no issue for security but if you are adding login functionality then you must add the logout functionality correctly.
3. Usmaan there is no need to use API you can easily manage the complete app like i have done in this tutorial.
Hi admin, how to do if I just want to show one student information?
Ice when you select any record there is only single student information will show on screen, Please explain your question more briefly ?
I want to register the data then edit the data I one only
Hi, admin, Is possible if I want like this? For example, I login as student A, I want to only student A detail and then click it, It will send detail to update interface to give user update. Because like now the tutorial is I login as student A but I still can change student B detail. So, is possible to do it? I can how to do?
If can how to do?*
Read my this tutorial this would help you : https://reactnativecode.com/click-filter-json-selected-listview-data-android-ios/
Yes it is possible John you need to open only student 1 detail after login read my this tutorial this would help you : https://reactnativecode.com/click-filter-json-selected-listview-data-android-ios/
Hi, admin. What do you mean by open only student 1 detail after login? Because in the tutorial, when there is data match with the SQL server. JSON will return ‘data match’ and app.js code will get the string data and check if ‘data match’ sucessfully arrived. So, where can we put on the validation? Is it in the php files?
Okay, I want to use that same version.
Hi,
I must say its a great tutorial, really well explained.
Is there any tutorial for todo app like project management tool with firestore database? Please help me out if have.
Thanks in advance! 🙂
Thanks for comment Priya, Firestore means firebase .
Yes. Cloud firestore/firebase.
Sure Priya, I will soon going to post tutorial on Firebase database with react native 🙂 .
Hi Admin, I need Authentication flow implementation help.
Eg, Once login, should go back to login screen or registration screen using back arrow/button. Please help me out.
Priya by default if you will login and press the back arrow then you should go back to login screen.
My typing mistake, I was saying that it should not go back to login screen.
What approach do I need to implement File uploading in react native?
Priya then you can read my this tutorial https://reactnativecode.com/finish-current-activity-route-screen/ using this you can close the login screen and move the new screen. If you want to upload file then you can also read my this tutorial : https://reactnativecode.com/upload-image-to-server-using-php-mysql/
Hello sir,
Please give me the github link.
Sir, do you have any idea of how to prevent user insert the same data into mysql database? For example there is a list of data display in a flatlist and I click the first data and click the add button so the first data will be inserted to another table. And When I click again the first data and click add again, it should display a warning msg say it already exist in the table already.
Jerry then you need to manually check using query that the current data is already existed or not.
I found the solution already, thank you for reply sir
Welcome Jerry 🙂 .
sir, how to delete record and go back and refresh page?
Kenny you can find the delete code in tutorial .
I solve the problem finally, thank you sir
Hello Admin, great work, but it seems there is an update to StackNavigation… Please can you update your code. Thank you.
Sure Ayodele i will update the code.
Hi! How did you solved the problem?
how do you try your code?
Simply copy the main App.js code into your own App.js file and run the code & one more thing in this tutorial i am using the older version of React Navigation library so you have to read their new documentation also.
How do you test your application?
Welcome 🙂 .
How to get the inserted values in the edit screen ?
what i mean is e.g: when i create/insert record of Student data, it will store in database table,
now i want to edit some thing from Student in the EDIT/Update Student Data it will go to Edit Screen and 1st get the inserted data inside each TextInput then it will update the particular data….
How to get the inserted data on the Edit Screen TextInput ?
Adnan in Edit Student Record Activity you can see i am entering the student details in Textinputs.
well Admin, i am going in specific detail…
On show student list activity list of different students are showing that is coming from database, there must be 2 button against each student these button are Edit and Delete, when you click on edit button the id of that particular student will go to the Edit Screen and now on Edit Screen you must get all the fields of that student and before editing the record it must show the previous details of that student inside the Input fields..
What i want is how to get those values inside the Input fields before editing the new details…. Hope you get my point…
Getting this error when run react app
./src/App.js
Line 420: ‘MyNewProject’ is not defined no-undef
Bro StackNavigator is deprecated you have to use createStackNavigator.
when you add fetch in app js you hosting php and database file or no ?
please answer my question
Idham the fetch function is called in main app.js file and the database files will upload on your web hosting server.
Hey there, thanks a lot for the code. Seems like I cannot insert my data into the database. I have edited all the database configurations tho.
Umar did you put your own server URL ?
At first I did put my localhost server, and yes I put my IP address without changing anything to the front end code except the stackNavigator. But it didn’t work. Then I tried to use web 000webhost but didn’t work either. It shows some JSON error. But when I used your server url It works fine. Really.
Umar please tell me what changes you have made ?
Hello admin
Can l find this project on github?
Sorry, The project is not uploaded on GitHub . But you can find all the files here in post.
Hi brother.
The code does not work in the code:
.then ((responseJson) => {Alert.alert (responseJson);})
.catch ((error) => {console.error (error);});
The error message is as follows:
JSON Parse error: Unrecognized token ‘<'
– node_modules promised immediate intro.js: 37: 14 in tryCallOne
– node_modules promised immediate intro.js: 123: 25 in
– … 8 more stack frames from framework internals
This in all functions.
How can I solve it?
Thanks
this error: Unrecognized token ‘<'
usually occurs when there's no response from the server. it happened to me when i forgot to update the url to my server
Thanks for quick answer 🙂 .
Anyone having an issue with ListView may want to try this.
componentDidMount() {
return fetch(‘https://yoursite.000webhostapp.com/Student/ShowAllStudentsList.php’)
.then((response) => response.json())
.then((responseJson) => {
//let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
isLoading: false,
dataSource: responseJson,
}, function () {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
return (
index.toString()}
renderItem={({ item }) =>
{item.student_name}
}
/>
);
that last code snippet was cut off I guess, here it is again.
return (
index.toString()}
renderItem={({ item }) =>
{item.student_name}
}
/>
);
ok my bad it must be getting caught in sanitation. any way I can leave a code block?
the json url is no longer available, please update
I will ASAP update the URL .
Great work Admin. Kudos. Do you have video version of the same.
Admin, may I ask how about the react navigation in the new version , v ^5 for this CRUD tutorial
Kelly i will soon make a tutorial with new React Navigation 5.x . Until than you can read this tutorial : https://reactnativecode.com/react-navigation-latest-version-5-x/
Thank’s for your work!
Tell me please how can i get data from mysql to Text (not to listview).
And another one question: how can I upload image to server and return link to MySQL without RN-fetch-blob, because wetch-blob doesn’t work in expo.
my email: [email protected]
Hello I am getting the error below, how do I go about it?
web Failed to compile.
C:/Users/admin/ExpoCLI/myproject/node_modules/@react-navigation/native/lib/module/Scrollables.js
Module not found: Can’t resolve ‘react-native-gesture-handler’ in ‘C:\Users\admin\ExpoCLI\myproject\node_modules\@react-navigation\native\lib\module’
INFO
01:11
Compiling…
ERROR
01:11
web Failed to compile.
C:/Users/admin/ExpoCLI/myproject/node_modules/@react-navigation/native/lib/module/Scrollables.js
Module not found: Can’t resolve ‘react-native-gesture-handler’ in ‘C:\Users\admin\ExpoCLI\myproject\node_modules\@react-navigation\native\lib\module’
ERROR
01:12
Unable to resolve “react-native-gesture-handler” from “node_modules\@react-navigation\native\lib\module\Scrollables.js”
ERROR
01:12
Building JavaScript bundle: error
Thank you
Haii Admin,
Thank you for the nice tutorial …
I Have followed the above steps i am getting the following errors .
TypeError: Object(…) is not a function
Module…/../../../../../../../../PearlPackaging/App.js
C:/Users/Priya Selvakumar/PearlPackaging/App.js:420
417 |
418 | }
419 |
> 420 | export default PearlPackaging = StackNavigator(
421 |
422 | {
423 |
View compiled
__webpack_require__
C:/Users/Priya Selvakumar/PearlPackaging/webpack/bootstrap:789
786 | };
787 |
788 | // Execute the module function
> 789 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 790 |
791 | // Flag the module as loaded
792 | module.l = true;
View compiled
fn
C:/Users/Priya Selvakumar/PearlPackaging/webpack/bootstrap:100
97 | );
98 | hotCurrentParents = [];
99 | }
> 100 | return __webpack_require__(request);
| ^ 101 | };
102 | var ObjectFactory = function ObjectFactory(name) {
103 | return {
View compiled
Module…/../../../../../../../../PearlPackaging/node_modules/expo/AppEntry.js
C:/Users/Priya Selvakumar/PearlPackaging/node_modules/expo/AppEntry.js:1
> 1 | import registerRootComponent from ‘expo/build/launch/registerRootComponent’;
2 |
3 | import App from ‘../../App’;
4 |
View compiled
__webpack_require__
C:/Users/Priya Selvakumar/PearlPackaging/webpack/bootstrap:789
786 | };
787 |
788 | // Execute the module function
> 789 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 790 |
791 | // Flag the module as loaded
792 | module.l = true;
View compiled
fn
C:/Users/Priya Selvakumar/PearlPackaging/webpack/bootstrap:100
97 | );
98 | hotCurrentParents = [];
99 | }
> 100 | return __webpack_require__(request);
| ^ 101 | };
102 | var ObjectFactory = function ObjectFactory(name) {
103 | return {
View compiled
0
http://localhost:19006/static/js/bundle.js:83445:18
__webpack_require__
C:/Users/Priya Selvakumar/PearlPackaging/webpack/bootstrap:789
786 | };
787 |
788 | // Execute the module function
> 789 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 790 |
791 | // Flag the module as loaded
792 | module.l = true;
View compiled
(anonymous function)
C:/Users/Priya Selvakumar/PearlPackaging/webpack/bootstrap:856
853 |
854 |
855 | // Load entry module and return exports
> 856 | return hotCreateRequire(0)(__webpack_require__.s = 0);
| ^ 857 |
View compiled
(anonymous function)
http://localhost:19006/static/js/bundle.js:860:10
How to Migrating React Native ListView to new FlatList in this Project???
Please Help me.
Thanks