How to get data from MySQL with React using PHP

To retrieve data from a MySQL database with React using PHP as the server-side scripting language, you can follow these steps:

Step 1: Set Up Your MySQL Database.

Ensure that you have a MySQL database with the necessary tables and data you want to retrieve. If you don't have a database, you can create one using tools like phpMyAdmin or by running SQL queries. Here's an example SQL query to create a simple "products" table:

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    price DECIMAL(10, 2) NOT NULL
);

INSERT INTO products (name, description, price)
VALUES ('Product 1', 'Description for Product 1', 19.99),
       ('Product 2', 'Description for Product 2', 29.99),
       ('Product 3', 'Description for Product 3', 39.99);

Step 2: Create a PHP Backend.

Create a PHP script to connect to the MySQL database and retrieve data. Save this script in a file (e.g., getData.php).

<?php
// Database configuration
$dbHost = 'localhost';
$dbUsername = 'your_username';
$dbPassword = 'your_password';
$dbName = 'your_database';

// Create a database connection
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check the connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve data from the "products" table
$sql = "SELECT * FROM products";
$result = $conn->query($sql);

$products = [];
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $products[] = $row;
    }
}

// Close the database connection
$conn->close();

// Return the data as JSON
header('Content-Type: application/json');
echo json_encode($products);
?>

Replace 'your_username', 'your_password', and 'your_database' with your actual database credentials.

Step 3: Set Up Your React App.

Set up a React application if you haven't already. You can use Create React App or any other React project setup method you prefer.

Step 4: Retrieve Data in React.

In your React component, use the fetch API or a library like axios to make an HTTP GET request to your PHP script to retrieve the data:

import React, { useState, useEffect } from 'react';

function App() {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    // Make an HTTP GET request to your PHP script
    fetch('http://localhost/path/to/your/getData.php')
      .then((response) => response.json())
      .then((data) => setProducts(data))
      .catch((error) => console.error('Error:', error));
  }, []);

  return (
    <div>
      <h1>Product List</h1>
      <ul>
        {products.map((product) => (
          <li key={product.id}>
            {product.name} - ${product.price}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;

Replace http://localhost/path/to/your/getData.php with the actual URL to your PHP script.

Step 5: Run Your React App.

Start your React development server to run your application.

npm start

This command will start your React application, and you should see a list of products retrieved from your MySQL database displayed in your React app.

Ensure that your PHP server is running and that you've configured CORS settings if your React app and PHP script are on different domains. Additionally, make sure to handle errors gracefully in your React component and implement proper error handling in your PHP script for production use.

Muhammad Alfaiz
Alfaiz 6 months ago
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x