As most of our reader requested we are finally posting this tutorial to Connect Run Apps Using Localhost PhpMyAdmin MySQL Database System in react native, Using this tutorial each of us can easily test our newly build react native apps with MySQL database using JSON. The main purpose of this tutorial is to making and testing the apps on our Local system so there is no need to create and upload all the stuff online, now we can test a complete JSON ListView application offline on local system but they do work like online. So let’s get started 🙂 .
Note :Â All the steps written in this tutorial must be follow and you need to download and install the XAMPP software.
Contents in this project Connect Run Apps Using Localhost PhpMyAdmin MySQL Database System in React Native iOS Android:
1. Before getting started we need to download and install the latest version on XAMPP software, This is very important for present tutorial because XAMPP gives the ability to our system by making and working like a Localhost computer, Here is the link.
2. After successfully downloaded we need to install it like any other normal software, Now after done installing start the XAMPP and start Apache and MySQL services . Now your system is ready to use like a local host computer.
1. Open your web browser(Mozilla Firefox or Google chrome) and type localhost/phpmyadmin in address bar to open the MySQL database panel.
2.Click on the New link to make a new MySQL database on your local system.
3. Now enter the database name as Flowers and hit the Create button.4. Now our database is successfully created, Next step is to crate table in your MySQL database. So select your newly created database from side panel.
5. Enter table name as flowers_name and select column as 2 .
6. Now we need to enter the table column names, column data type, length and select id as primary key with Auto increment.
7. Here you go now the table has been created successfully, Now we need to insert some data inside it. So select your table and click on Insert button.
8. Insert some records as i did in below screenshot and hit the Go button.
Screenshot of Table after inserting some records:
4. Create PHP Script to Convert MySQL database data into JSON :
Next step is to create 2 PHP files named as DBConfig.php and FlowersList.php .
DBConfig.php :Â This file contain all the useful information like Database name, database username, database password and database host name.
FlowersList.php : This file would convert the MySQL database data into JSON format.
Code for DBConfig.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php //Define your host here. $HostName = "localhost"; //Define your database name here. $DatabaseName = "flowers"; //Define your database username here. $HostUser = "root"; //Define your database password here. $HostPass = ""; ?> |
Code for FlowersList.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); } $sql = "SELECT * FROM flowers_name"; $result = $conn->query($sql); if ($result->num_rows >0) { while($row[] = $result->fetch_assoc()) { $tem = $row; $json = json_encode($tem); } } else { echo "No Results Found."; } echo $json; $conn->close(); ?> |
5. Now we need to make a folder named as Flowers_Site inside C:\xampp\htdocs\ folder.
6. Copy both DBConfig.php and FlowersList.php file inside the Flowers_Site folder.
8. Here you go, next step is to open the Command Prompt and execute ipconfig command. This command would show us our local computer system IP Address.
Note :Â If you are connected to WiFi then select the IPv4 address under Wireless LAN adapter Wi-Fi. If you are connected to LAN then selected IPv4 address under Ethernet adapter.
9. After getting the IP Address and copied all the files into the folder our JSON is ready to parse with react native app but we need to make sure the URL is working correctly so we need to open the URL in our web browserÂ
http://192.168.2.103/Flowers_Site/FlowersList.php , This is my URL you need to put your local IP address here. We would use this URL in our react native app.
1. Import StyleSheet, ActivityIndicator, ListView, Text, View and Alert component in your project.
1 2 3 |
import React, { Component } from 'react'; import { StyleSheet, ActivityIndicator, ListView, Text, View, Alert } from 'react-native'; |
2. Create constructor() in your project and make a State named as isLoading with true Boolean value, This state is used to show Activity loading indicator while loading data from server.
1 2 3 4 5 6 7 8 9 10 11 |
constructor(props) { super(props); this.state = { isLoading: true, } } |
3. Create componentDidMount() method and inside it we would make the fetch API to parse JSON from local server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
componentDidMount(){ return fetch('http://192.168.2.103/Flowers_Site/FlowersList.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); }); } |
4. Create a function named as GetItem() to show the selected flower name when user click the ListView item.
1 2 3 4 5 |
GetItem (flower_name) { Alert.alert(flower_name); } |
5. Create another function named as ListViewItemSeparator(), This function would render a horizontal line between each ListView element.
1 2 3 4 5 6 7 8 9 10 11 |
ListViewItemSeparator = () => { return ( <View style={{ height: 2, width: "100%", backgroundColor: "#000", }} /> ); } |
6. Put a IF condition inside render’s block, using this we would show the Activity Indicator with State value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
render() { if (this.state.isLoading) { return ( <View style={{flex: 1, paddingTop: 20}}> <ActivityIndicator /> </View> ); } return ( ); } |
7. Creating the ListView component inside the render’s return block.
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 |
render() { if (this.state.isLoading) { return ( <View style={{flex: 1, paddingTop: 20}}> <ActivityIndicator /> </View> ); } return ( <View style={styles.MainContainer}> <ListView dataSource={this.state.dataSource} renderSeparator= {this.ListViewItemSeparator} enableEmptySections = {true} renderRow={(rowData) => <Text style={styles.rowViewContainer} onPress={this.GetItem.bind(this, rowData.flower_name)} >{rowData.flower_name}</Text>} /> </View> ); } |
8. Creating Style.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
const styles = StyleSheet.create({ MainContainer :{ justifyContent: 'center', flex:1, margin: 10 }, rowViewContainer: { fontSize: 20, paddingRight: 10, paddingTop: 10, paddingBottom: 10, } }); |
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 |
import React, { Component } from 'react'; import { StyleSheet, ActivityIndicator, ListView, Text, View, Alert } from 'react-native'; export default class Project extends Component { constructor(props) { super(props); this.state = { isLoading: true, } } GetItem (flower_name) { Alert.alert(flower_name); } componentDidMount(){ return fetch('http://192.168.2.103/Flowers_Site/FlowersList.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); }); } ListViewItemSeparator = () => { return ( <View style={{ height: 2, width: "100%", backgroundColor: "#000", }} /> ); } render() { if (this.state.isLoading) { return ( <View style={{flex: 1, paddingTop: 20}}> <ActivityIndicator /> </View> ); } return ( <View style={styles.MainContainer}> <ListView dataSource={this.state.dataSource} renderSeparator= {this.ListViewItemSeparator} enableEmptySections = {true} renderRow={(rowData) => <Text style={styles.rowViewContainer} onPress={this.GetItem.bind(this, rowData.flower_name)} >{rowData.flower_name}</Text>} /> </View> ); } } const styles = StyleSheet.create({ MainContainer :{ justifyContent: 'center', flex:1, margin: 10 }, rowViewContainer: { fontSize: 20, paddingRight: 10, paddingTop: 10, paddingBottom: 10, } }); |
Screenshots:
i try this, but always “Network request failed”, how to solve it ?
On which platform you have testing this app ?
is this possible with pdo
Sorry i haven’t tried it with pdo .
admin can you please make a tutorial for mysql for where query in react native with mysql
Sajid please explain your query ?
sir can you will make video of how db connection are going in linux
Nagesh please be more specific you want me to make a video on Connecting linux OS to react native app .
i have problem.. the json parse error: Unrecognized token ‘<'
i always got this error after try copy your code.. i try it using ip address to real devices.
Bro you need to first connect your system to WiFi network then copy the IP from CMD.
sir..the JSON parse error: unrecognized token ‘<'… I make the step same with you but I got this kind of error.
Hi boss, may i know why its come out JSON Parse error: Unrecognized token ‘<'
Try to start the internet connection in Emulator.
Thanx Man l truely appreciate
Welcome Josh 🙂 .
May i know if i want insert View component which same as shopping card, how could i do?
my apps is running but its only display blank listview can you help me?
Hanif you are using my database(Which i have created in example) or your own, If there is no error then maybe you should put your data name in rowData.flower_name (Here you need to put your table column name which you want to show in listview) .
{ [TypeError: Network request failed]
03-20 18:01:56.472 4749 5006 I ReactNativeJS: line: 24080,
03-20 18:01:56.472 4749 5006 I ReactNativeJS: column: 31,
03-20 18:01:56.472 4749 5006 I ReactNativeJS: sourceURL: ‘http://10.0.2.2:8081/index.delta?platform=android&dev=true&minify=false’ }
Muzaffar please tell me which internet connection you are using WiFi or landline ?
Hi, someone got save data from a DB on a local variable
When I put a URL that you provided without a tutorial, but using the IP of my computer, it says that the object was not found. Would you tell me why?
Any did you put all the files same as me also.
I managed to solve. Thanks
I got this error
Network request failed
– node_modules\react-native\Libraries\vendor\core\whatwg-fetch.js:504:29 in onerror
– node_modules\event-target-shim\lib\event-target.js:172:43 in dispatchEvent
– … 8 more stack frames from framework internals
Clydea what changes you have made in code ?
Can you place the folder for the app project anywhere in PC or must it be within the folder where php files are in htdocs?
The react native app project folder can be placed in any drive but the php files folder must be place in htdocs .
Does this work with Expo?
Sorry Delroy i have not test this with EXPO but it works fine with local system.
Help me with the following problem:
“Network request failed”
Nett your system is connected to wifi network or LAN.
yes, it’s connected to wifi network
Then you should use Ip address under wireless lan adapter, Did you put all the files in htdocs folder ? like i did .
Yes, but I am using Wamp Server; however I can access the address through the chrome browser perfectly. The problem is only with the apication. Because it seems that she does not access that address, and I am using the same network. Yes, all the files in www folder
Net you have to put your ip_address/folder_name/file name like path.
application *
Thank for this helpfull tutorial
Invariant Violation: ListView has been removed from React Native..
You should use Flat List instead of List View .
I try this, but always “Network request failed”, how to solve it?
Son Tran which iP address you used ?
I got this error in my phone
Network Request Failed
i am using wifi connection
and already test it using postman
Hi This is Sanker, i am getting bellow error can you please help on this
error in console block:
Access to fetch at ‘http://192.168.0.105/Flowers_Site/FlowersList.php’ from origin ‘http://localhost:19006’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.
App.js:28 GET http://192.168.0.105/Flowers_Site/FlowersList.php net::ERR_FAILED
index.js:1 TypeError: Failed to fetch
Hello brother, It shows like List view has been removed from React Native. Can I use this in flatist?
If yes how can I pass the responseJson to state please reply me Brother.
Hello brother, It shows like List view has been removed from React Native. Can I use this in flatist?
If yes how can I pass the responseJson to state please reply me Brother..
How can I make it live for free from localhost???
Plz tell me
ERROR [TypeError: Network request failed]
I am also getting this same error. Hello admin most of the people are getting the same error. can you provide a solution for this?
Exactly what I am looking for, thanks alot it save my time, just did it in 5min following this, Thanks!!!
Welcome Jamal 🙂 ;