Integrating AG Grid with PHP is a powerful way to handle large datasets with a modern, high-performance UI. Because PHP is a server-side language and AG Grid is a client-side JavaScript library, the bridge between them is typically a RESTful API that handles data fetching and updates. The Modern Architecture
In an updated stack, you move away from rendering HTML tables on the server. Instead, PHP acts as the backend engine—using a framework like Laravel or a simple Slim app—to serve JSON. AG Grid sits on the frontend, consuming that JSON. This separation allows for "Server-Side Row Model" features, where the grid only loads the data visible to the user, making it capable of handling millions of rows without crashing the browser. Data Fetching and CRUD An effective implementation involves a few key steps:
The API Endpoint: A PHP script queries your database (like MySQL) and returns the result as json_encode($data).
The Grid Configuration: On the frontend, you define columnDefs and use the fetch() API to pull from your PHP endpoint.
Updates: By using AG Grid's onCellValueChanged event, you can send an asynchronous POST or PUT request back to a PHP script to save changes to the database instantly. Security and Performance
Modern examples prioritize prepared statements (PDO) in PHP to prevent SQL injection. Additionally, with the latest AG Grid updates, you can leverage Integrated Charts and Advanced Filtering, which requires passing complex filter objects from the grid to your PHP logic to dynamically build the SQL query.
Building a robust data grid in PHP doesn't have to be complicated. By combining AG Grid's powerful frontend features with a clean PHP backend, you can handle massive datasets with ease.
This guide provides a modern, updated approach to integrating AG Grid with PHP and MySQL using the latest Fetch API and JSON best practices. 🏗️ The Architecture
To create a functional AG Grid PHP example, you need three core components: The Database: A MySQL table to store your data.
The Backend (PHP): A script to fetch data and return it as JSON. aggrid php example updated
The Frontend (HTML/JS): The AG Grid configuration that consumes the JSON. 1. Setup the Database
First, create a simple table and populate it with sample data.
CREATE DATABASE grid_db; USE grid_db; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), email VARCHAR(100), role VARCHAR(50), status VARCHAR(20) ); INSERT INTO users (name, email, role, status) VALUES ('Alice Smith', 'alice@example.com', 'Admin', 'Active'), ('Bob Jones', 'bob@example.com', 'User', 'Inactive'), ('Charlie Brown', 'charlie@example.com', 'Editor', 'Active'); Use code with caution. 2. Create the Backend (data.php)
This script connects to your database and outputs the results in a format AG Grid understands. We use PDO for security and json_encode for the response.
PDO::ATTR_ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; try $pdo = new PDO($dsn, $user, $pass, $options); $stmt = $pdo->query("SELECT id, name, email, role, status FROM users"); $data = $stmt->fetchAll(); echo json_encode($data); catch (\PDOException $e) echo json_encode(['error' => $e->getMessage()]); ?> Use code with caution. 3. Build the Frontend (index.html)
In this updated version, we use the AG Grid Community CDN and the modern Fetch API to retrieve our PHP data.
To keep the grid updated after any PHP-side change (e.g., another user updates data), implement polling or WebSockets. A simple approach:
setInterval(() =>
gridOptions.api.refreshServerSideStore( purge: true );
, 30000); // refresh every 30 seconds
Or use AG Grid Transaction Updates for optimistic UI: Integrating AG Grid with PHP is a powerful
// After successful update via PHP
gridOptions.api.applyServerSideTransaction(
update: [updatedRowData]
);
Create a MySQL database and add a table with some sample data. For this example, we'll use a simple table called "employees" with the following columns:
| id | name | email | department |
| --- | --- | --- | --- |
| 1 | John Smith | john.smith@example.com | Sales |
| 2 | Jane Doe | jane.doe@example.com | Marketing|
| 3 | Bob Brown | bob.brown@example.com | IT |
Status: [Draft / Ready for Discussion]
Context: Integration of AG Grid (JavaScript) with a PHP backend for data retrieval.
Objective: Ensure data is delivered efficiently, securely, and in the correct format for the grid to consume.
The updated PHP example already includes this logic, but here’s how AG Grid sends each type:
| Action | AG Grid Request parameter | PHP handling |
|--------|--------------------------|---------------|
| Sort | sortModel: [colId:"price", sort:"desc"] | Builds ORDER BY price DESC |
| Text filter | filterModel: product_name: filter: "laptop", type: "contains" | product_name LIKE '%laptop%' |
| Number filter | filterModel: price: filter: 100, type: "greaterThan" | price > 100 |
| Date filter | filterModel: last_updated: dateFrom: "2024-01-01" | DATE(last_updated) >= '2024-01-01' |
| Pagination | startRow: 200, endRow: 300 | LIMIT 100 OFFSET 200 |
Important: Never trust client-side input. Always use prepared statements as shown above.
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
require_once 'db.php'; // PDO connection
$request = json_decode(file_get_contents('php://input'), true);
$startRow = $request['startRow'] ?? 0;
$endRow = $request['endRow'] ?? 100;
$sortModel = $request['sortModel'] ?? [];
$filterModel = $request['filterModel'] ?? []; Or use AG Grid Transaction Updates for optimistic
$limit = $endRow - $startRow;
$offset = $startRow;
// Base query
$sql = "SELECT id, name, email, created_at FROM users WHERE 1=1";
$params = [];
// Apply filters
foreach ($filterModel as $field => $filter)
if ($filter['filterType'] === 'text')
$sql .= " AND $field LIKE :$field";
$params[":$field"] = '%' . $filter['filter'] . '%';
// Apply sorting
if (!empty($sortModel))
$orderBy = [];
foreach ($sortModel as $sort)
$orderBy[] = "$sort['colId'] $sort['sort']";
$sql .= " ORDER BY " . implode(', ', $orderBy);
// Get total row count
$countSql = preg_replace('/SELECT.FROM/', 'SELECT COUNT() as total FROM', $sql, 1);
$stmt = $pdo->prepare($countSql);
$stmt->execute($params);
$totalRows = $stmt->fetch(PDO::FETCH_ASSOC)['total'];
// Add pagination
$sql .= " LIMIT $limit OFFSET $offset";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode([
'rows' => $rows,
'lastRow' => $totalRows
]);