How to connect to SQL database with react?

How to connect to SQL database with react?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

You cannot write PHP inside a React application to connect to a SQL database. This is a fundamental architectural shift that often confuses developers moving from server-side rendering (like traditional PHP/HTML sites) to client-side JavaScript frameworks. In your previous setup, the PHP code lived on the server, executed against the database, and returned an HTML response directly to the browser. React applications, by contrast, run entirely in the browser as JavaScript. They do not have access to the server's filesystem or environment variables where your database credentials are stored.

Attempting to place a <php> tag inside a .js file or trying to import PHP logic into a React component will result in syntax errors because the browser only understands JavaScript, JSON, and CSS. To achieve your goal of fetching data for your React app, you must decouple the data retrieval logic from the view layer. This means keeping the database connection on the server (where it belongs) and having your React app communicate with that server via an API.

The standard approach involves creating a separate endpoint in your PHP application that acts as a bridge to your SQL database. Instead of including connection.php directly in your React build process, you create a route—say, /api/data—on your PHP side. This file uses the same mysqli_connect logic you already know:

<?php
// api/data.php
header('Content-Type: application/json');

$conn = mysqli_connect($serverIP, $dbusername, $dbpassword, $dbname);

if (mysqli_errno($conn)) {
    die(json_encode(['error' => 'MySQL error: ' . mysqli_error($conn)]));
}

// Execute your query and fetch results
$result = mysqli_query($conn, "SELECT * FROM your_table");
$data = [];

while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

mysqli_close($conn);

echo json_encode($data);
?>

Once this endpoint is running on your server, your React component can fetch the data using the Fetch API or axios. You would make a request to that URL, parse the JSON response, and then render the results. For example:

import { useEffect, useState } from 'react';

function MyComponent() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    fetch('/api/data') // Ensure this matches your PHP route
      .then((response) => response.json())
      .then((result) => {
        setData(result);
        setLoading(false);
      })
      .catch((error) => console.error('Error fetching data:', error));
  }, []);

  if (loading) return <p>Loading...</p>;
  return (
    <ul>
      {data.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}

This separation ensures security. Your database credentials remain hidden in the server-side PHP file and never touch the client-side JavaScript bundle, preventing malicious users from sniffing your connection strings.

If you are looking for a place to review your code and get tips on improvement, consider joining communities like Stack Overflow for specific technical questions or GitHub for repository feedback. These platforms allow you to share snippets and receive constructive criticism on architecture and implementation details.

While this manual setup works well for simple projects, if you find yourself needing more robust API handling, authentication, or database migrations, the Laravel framework might be a natural next step. Since your current site uses PHP, transitioning to Laravel would provide built-in tools for creating RESTful APIs and managing database connections securely without reinventing the wheel. It handles the boilerplate of connecting to MySQL, routing requests, and returning JSON responses out of the box, allowing you to focus on building your React frontend logic rather than managing raw PHP scripts.

Our network