Retrieving Data from MySQL Database in React JS: A Guide to React CRUD with PHP API and MySQL – Part 5

Posted by

<!DOCTYPE html>

Fetch data From MySQL Database in React JS

Fetch data From MySQL Database in React JS

React JS is a popular front-end library for building interactive user interfaces. In this article, we will see how to fetch data from a MySQL database in a React JS application.

Step 1: Create a PHP API to communicate with MySQL

First, we need to create a PHP API that will communicate with the MySQL database and fetch the data. Here is an example of a simple PHP API:

“`php
connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}

// Fetch data from database
$sql = “SELECT * FROM table_name”;
$result = $conn->query($sql);

if ($result->num_rows > 0) {
$data = array();
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode($data);
} else {
echo “0 results”;
}

$conn->close();

?>
“`

Step 2: Create a React JS component to fetch and display data

Now, we need to create a React JS component that will fetch the data from the PHP API and display it on the screen. Here is an example of a simple React component:

“`jsx
import React, { useEffect, useState } from ‘react’;

const App = () => {
const [data, setData] = useState([]);

useEffect(() => {
fetch(‘http://localhost/api.php’)
.then(response => response.json())
.then(data => setData(data));
}, []);

return (

Data from MySQL database:

    {data.map(item => (

  • {item.name}
  • ))}

);
};

export default App;
“`

In this component, we use the useState and useEffect hooks to fetch the data from the PHP API when the component mounts. We then use the map function to iterate over the data and display it in a list.

Step 3: Run the React JS application

Finally, we need to run the React JS application to see the data from the MySQL database. To do this, you can run the following command in the terminal:

“`bash
npm start
“`

This will start the React development server and open the application in your browser. You should now see the data from the MySQL database displayed on the screen.

That’s it! You have successfully fetched data from a MySQL database in a React JS application. Keep exploring and building awesome applications with React JS!

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@SADDAM96478
5 months ago

Sir mera portal me retailer ko add nahi kar pa Raha hoon. Issue user not created