Updated | Aggrid Php Example
Integrating AG Grid with PHP remains a top choice for developers building data-heavy enterprise dashboards. While AG Grid is a client-side powerhouse, connecting it to a PHP backend (like Laravel or raw PHP with PDO) allows you to handle millions of rows through server-side processing.
This guide focuses on an updated implementation for 2025, utilizing modern PHP best practices and AG Grid's latest Server-Side Row Model (SSRM) features. 1. The Strategy: Server-Side Row Model (SSRM)
For large datasets, don't load everything at once. Use the SSRM to fetch data in blocks as the user scrolls.
Client-side: AG Grid sends a JSON request containing pagination, sorting, and filtering state.
Server-side (PHP): A PHP script parses this JSON, builds a dynamic SQL query, and returns only the requested "slice" of data. 2. Updated PHP Backend Implementation (Laravel Example)
Modern adapters like the AG Grid Server Side Adapter for Laravel simplify this by automatically transforming grid requests into Eloquent queries. Example Controller Snippet:
use App\Models\User; use Clickbar\AgGrid\Requests\AgGridGetRowsRequest; class UserController extends Controller public function getRows(AgGridGetRowsRequest $request) // Automatically handles filtering, sorting, and pagination return AgGridQueryBuilder::forRequest($request, User::query()) ->get(); Use code with caution. Copied to clipboard JavaScript Grid: Server-Side Row Model - AG Grid
This script acts as your API. It connects to a database and returns data in JSON format, which AG Grid expects. query( "SELECT id, name, email, role FROM users" ); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); json_encode($data); (PDOException $e) json_encode([ => $e->getMessage()]); ?> Use code with caution. Copied to clipboard 2. The Frontend (index.html)
You include the AG Grid library via CDN and use JavaScript to initialize the grid and fetch data from your PHP script. < >AG Grid PHP Example "https://jsdelivr.net" "ag-theme-alpine" "height: 500px; width:100%;" > const columnDefs = [ field: , sortable: true, filter: true , field:
, sortable: true, filter: true, editable: true , field: , filter: true , field:
];
const gridOptions =
columnDefs: columnDefs,
pagination: true,
// Capture updates to cells
onCellValueChanged: (params) =>
console.log( 'Data updated:'</p>
, params.data); // Here you would use fetch() to POST updates back to a PHP script ;
// Initialize the grid
const gridDiv = document.querySelector(</p>
); const gridApi = agGrid.createGrid(gridDiv, gridOptions);
// Fetch data from PHP backend
fetch( 'data.php'</p>
) .then(response => response.json()) .then(data => gridApi.setGridOption( , data));
event. You can then send the updated row data back to a PHP script using Grid Methods
: For more complex updates, such as programmatically changing a single cell, you can use grid API methods like rowNode.setDataValue(col, value) Row Selection
: If you need to perform actions on specific rows, enable selection and use gridApi.getSelectedRows() to retrieve the data for processing.
For developers who prefer a more "plug-and-play" PHP solution, alternatives like offer simplified rendering with fewer lines of code. PHP code for handling the POST request to save these grid updates to your database? How to get the data of selected rows in ag-Grid
How to get the data of selected rows in AG Grid * Enable Row Selection. Enable row selection in AG Grid using the grid options. .. AG Grid Blog JavaScript Data Grid - Updating Data - AG Grid
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.
Integrating AG Grid with PHP allows you to build high-performance, enterprise-grade data tables with features like server-side pagination, sorting, and filtering. This guide provides a modern example of connecting AG Grid to a PHP/MySQL backend for a full CRUD (Create, Read, Update, Delete) experience. 1. Database and Environment Setup
Before writing code, ensure you have a local server like XAMPP running with Apache and MySQL.
Database Preparation:Create a table named products to store your grid data: aggrid php example updated
CREATE DATABASE inventory_db; USE inventory_db; CREATE TABLE products ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, category VARCHAR(100), price DECIMAL(10, 2) ); Use code with caution. 2. The Frontend: AG Grid Implementation
Use the AG Grid Community edition via CDN for a quick setup. index.html:
Use code with caution. 3. The Backend: PHP & MySQL API
Your PHP scripts will handle data retrieval and updates using JSON as the bridge.
fetch.php (Read Operation):This script retrieves data from MySQL and returns it to the grid as a JSON array.
query("SELECT * FROM products"); echo json_encode($result->fetch_all(MYSQLI_ASSOC)); ?> Use code with caution.
update.php (Update Operation):When a cell is edited in the grid, this script receives the updated row data.
prepare("UPDATE products SET name=?, category=?, price=? WHERE id=?"); $stmt->bind_param("ssdi", $data['name'], $data['category'], $data['price'], $data['id']); $stmt->execute(); ?> Use code with caution. 4. Advanced: Server-Side Row Model (SSRM)
Implementing AG Grid with PHP involves a two-part architecture: a PHP backend to serve data (usually in JSON format) and a JavaScript frontend to render the grid. 1. The PHP Backend (data.php)
Your PHP script should fetch data from a database and return it as a JSON array. This is the "updated" way to handle modern grid requests.
query("SELECT id, name, model, price FROM cars"); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); // Output as JSON for AG Grid echo json_encode($results); catch (PDOException $e) echo json_encode(['error' => $e->getMessage()]); ?> Use code with caution. Copied to clipboard 2. The Frontend Layout (index.html)
Use the latest AG Grid Community Edition via CDN. The script fetches data from your PHP file using fetch().
Use code with caution. Copied to clipboard Key Update Notes
Grid Initialization: In newer versions (v31+), use agGrid.createGrid() instead of the older new agGrid.Grid().
Data Updates: Use gridApi.setGridOption('rowData', data) to dynamically refresh the grid.
Server-Side Operations: For massive datasets (millions of rows), consider AG Grid Enterprise which allows PHP to handle filtering and sorting directly on the server. Angular Grid: Upgrading to AG Grid 33.0
AG Grid PHP Example: A Comprehensive Guide to Implementing AG Grid with PHP
AG Grid is a powerful, feature-rich JavaScript data grid that allows developers to create complex, interactive tables with ease. While AG Grid is primarily a JavaScript library, it can be seamlessly integrated with PHP to create robust, data-driven applications. In this article, we'll explore an updated AG Grid PHP example, demonstrating how to implement AG Grid with PHP to create a dynamic, data-driven grid.
What is AG Grid?
AG Grid is a popular JavaScript library used to create interactive, feature-rich data grids. It offers a wide range of features, including support for large datasets, customizable columns, row selection, filtering, sorting, and more. AG Grid is highly customizable and can be easily integrated with various frameworks and libraries, including PHP.
Why Use AG Grid with PHP?
PHP is a popular server-side language used for web development, and AG Grid can be used to create dynamic, data-driven grids that interact with PHP applications. By integrating AG Grid with PHP, developers can leverage the strengths of both technologies to create powerful, data-driven applications. Some benefits of using AG Grid with PHP include:
- Dynamic data rendering: AG Grid can be used to render dynamic data from a PHP database, allowing developers to create real-time, data-driven applications.
- Customizable columns: AG Grid's columns can be customized using PHP, allowing developers to create tailored data grids that meet specific requirements.
- Server-side filtering and sorting: AG Grid can be integrated with PHP to perform server-side filtering and sorting, reducing the amount of data transferred between the client and server.
AG Grid PHP Example: Updated
In this example, we'll create a simple AG Grid application that interacts with a PHP database. Our application will display a grid of data, allow users to filter and sort data, and perform server-side filtering and sorting.
Step 1: Install AG Grid
To get started, download the AG Grid library from the official website. For this example, we'll use the community edition of AG Grid.
Step 2: Create a PHP Database
Create a simple PHP database using MySQL or your preferred database management system. For this example, we'll use a simple database with a single table called "employees".
CREATE TABLE employees (
id INT PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255),
department VARCHAR(255)
);
Step 3: Create a PHP Backend
Create a PHP backend that will interact with the AG Grid application. Our backend will consist of two files: grid.php and data.php.
grid.php
<?php
// Include the AG Grid library
require_once 'ag-grid-community.js';
// Define the grid columns
$columns = [
['headerName' => 'Name', 'field' => 'name'],
['headerName' => 'Email', 'field' => 'email'],
['headerName' => 'Department', 'field' => 'department']
];
// Define the grid options
$options = [
'columnDefs' => $columns,
'rowData' => []
];
// Create the grid
$grid = new ag_grid($options);
// Render the grid
echo $grid->render();
data.php
<?php
// Define the database connection settings
$dbHost = 'localhost';
$dbUsername = 'username';
$dbPassword = 'password';
$dbName = 'database';
// Connect to the database
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check for connections errors
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Retrieve the data from the database
$sql = "SELECT * FROM employees";
$result = $conn->query($sql);
// Fetch the data
$data = [];
while ($row = $result->fetch_assoc())
$data[] = $row;
// Close the database connection
$conn->close();
// Output the data in JSON format
header('Content-Type: application/json');
echo json_encode($data);
Step 4: Integrate AG Grid with PHP
Update the grid.php file to integrate AG Grid with the PHP backend.
<?php
// Include the AG Grid library
require_once 'ag-grid-community.js';
// Define the grid columns
$columns = [
['headerName' => 'Name', 'field' => 'name'],
['headerName' => 'Email', 'field' => 'email'],
['headerName' => 'Department', 'field' => 'department']
];
// Define the grid options
$options = [
'columnDefs' => $columns,
'rowData' => []
];
// Create the grid
$grid = new ag_grid($options);
// Fetch the data from the PHP backend
$dataUrl = 'data.php';
$data = json_decode(file_get_contents($dataUrl), true);
// Update the grid data
$options['rowData'] = $data;
// Render the grid
echo $grid->render();
Step 5: Add Filtering and Sorting
To add filtering and sorting, update the grid.php file to include the following code.
<?php
// Include the AG Grid library
require_once 'ag-grid-community.js';
// Define the grid columns
$columns = [
['headerName' => 'Name', 'field' => 'name', 'filter' => 'agTextColumnFilter'],
['headerName' => 'Email', 'field' => 'email', 'filter' => 'agTextColumnFilter'],
['headerName' => 'Department', 'field' => 'department', 'filter' => 'agTextColumnFilter']
];
// Define the grid options
$options = [
'columnDefs' => $columns,
'rowData' => [],
'pagination' => true,
'paginationAutoPageSize' => true
];
// Create the grid
$grid = new ag_grid($options);
// Fetch the data from the PHP backend
$dataUrl = 'data.php';
$data = json_decode(file_get_contents($dataUrl), true);
// Update the grid data
$options['rowData'] = $data;
// Add server-side filtering and sorting
if (isset($_GET['filter']))
$filter = $_GET['filter'];
$data = [];
// Apply the filter
foreach ($data as $row)
// Render the grid
echo $grid->render();
Conclusion
In this updated AG Grid PHP example, we've demonstrated how to integrate AG Grid with a PHP backend to create a dynamic, data-driven grid. We've covered the basics of AG Grid, including column definitions, grid options, and data rendering. We've also shown how to add filtering and sorting to the grid using server-side processing.
By following this example, developers can create powerful, data-driven applications using AG Grid and PHP. With its extensive feature set and customization options, AG Grid is an ideal choice for developers looking to create complex, interactive data grids.
Further Reading
- AG Grid Documentation: https://www.ag-grid.com/javascript-data-grid/
- AG Grid PHP Example: https://github.com/ag-grid/ag-grid-php-example
- PHP Documentation: https://www.php.net/docs.php
Building a High-Performance Data Grid: AG Grid & PHP (2026 Guide)
When your dataset grows from hundreds to hundreds of thousands of rows, client-side rendering isn't enough. You need a robust server-side strategy. Below is an updated guide and example for integrating AG Grid (v35+) 1. The Frontend: Modern AG Grid Setup For 2026, we utilize the Server-Side Row Model (SSRM)
. This allows the grid to only fetch the data it needs to display, rather than loading the entire database at once. < "https://jsdelivr.net" "height: 500px; width: 100%;" "ag-theme-alpine" > const columnDefs = [ field: 'agNumberColumnFilter' , field: 'agTextColumnFilter' , field: , field:
];
const gridOptions =
columnDefs: columnDefs,
rowModelType: 'serverSide'</p>
, // Enables SSRM pagination: true, paginationPageSize: , cacheBlockSize: ;
const gridDiv = document.querySelector(</p>
); const api = agGrid.createGrid(gridDiv, gridOptions);
// Fetch data from PHP backend
const datasource =
getRows: (params) =>
fetch( 'datasource.php' ,
method:</p>
, body: JSON.stringify(params.request), headers: 'Content-Type' 'application/json'
) .then(response => response.json()) .then(data => params.success( rowData: data.rows, rowCount: data.total ); ) .catch(error => params.fail()); ;
api.setGridOption( 'serverSideDatasource' , datasource);
</ Use code with caution. Copied to clipboard 2. The Backend: Scalable PHP Logic Your PHP script must handle the filterModel startRow/endRow parameters sent by AG Grid. Using is critical for security to prevent SQL injection. // datasource.php 'Content-Type: application/json' );
$input = json_decode(file_get_contents( 'php://input' ), true);
$startRow = $input[ 'startRow' ; $endRow = $input[ ; $limit = $endRow - $startRow; // Database Connection 'mysql:host=localhost;dbname=sports_db' // 1. Build the WHERE clause from AG Grid's filterModel " WHERE 1=1 " 'filterModel' 'filterModel' $col => $filter) // Simple example for text filter 'filterType' ) $where .= " AND $col LIKE " . $pdo->quote( . $filter[ ); } // 2. Fetch Paginated Data "SELECT * FROM athletes $where LIMIT :start, :limit" ; $stmt = $pdo->prepare($sql); $stmt->bindValue( , (int)$startRow, PDO::PARAM_INT); $stmt->bindValue(
, (int)$limit, PDO::PARAM_INT); $stmt->execute(); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // 3. Get Total Record Count for Pagination UI $totalSql = "SELECT COUNT(*) FROM athletes $where" ; $total = $pdo->query($totalSql)->fetchColumn(); json_encode([ => (int)$total ]); Use code with caution. Copied to clipboard Key Considerations for 2026 Version Updates : AG Grid v35 introduces improved Formula Editors BigInt support , making it ideal for financial PHP applications. : Always use prepared statements $pdo->quote() when handling filterModel keys to prevent malicious SQL injections. State Management : If you are using modern PHP frameworks like , consider leveraging its built-in paginators to simplify the server-side Excel export ChatGPT or Copilot – which is better for PHP development? Integrating AG Grid with PHP remains a top
Integrating AG Grid with a PHP backend allows you to handle massive datasets with high-performance features like filtering, sorting, and pagination. Because AG Grid is a client-side library, the "PHP connection" is actually an API bridge where PHP serves JSON data to the grid. Building a Modern AG Grid & PHP Integration 🛠️ The Stack Frontend: AG Grid (Community or Enterprise) Backend: PHP 8.x (Vanilla or Framework) Database: MySQL / PostgreSQL Communication: Fetch API (JSON) 1. The Frontend (index.html)
You need to define the grid container and tell AG Grid where to fetch the data.
Use code with caution. Copied to clipboard 2. The Backend (data.php)
Your PHP script acts as a data provider. It queries the database and returns a JSON array.
query("SELECT id, name, email, created_at FROM users"); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); // Send JSON response echo json_encode($results); catch (PDOException $e) http_response_code(500); echo json_encode(['error' => $e->getMessage()]); ?> Use code with caution. Copied to clipboard 🚀 Key Optimization Strategies 🔹 Server-Side Row Model (SSRM)
For datasets with millions of rows, don't load everything at once.
Client side: Requests a specific "block" of rows (e.g., rows 100-200). PHP side: Uses LIMIT and OFFSET in the SQL query. Benefit: Keeps the browser memory usage low. 🔹 Security Best Practices
PDO Prepared Statements: Always use prepared statements to prevent SQL injection.
CORS: If your frontend and backend are on different domains, configure Access-Control-Allow-Origin headers.
Sanitization: Use json_encode() to ensure data types are preserved correctly. 🔹 Handling Updates (CRUD) To make the grid editable: Enable editable: true in columnDefs. Use the onCellValueChanged event in AG Grid.
Send a POST or PUT request to a save.php script with the updated row data. 💡 Why this works in 2026
Modular JS: Works with Vite, Webpack, or simple tags.
PHP 8 Attributes: Can be used to map database entities directly to JSON.
Performance: AG Grid handles the DOM rendering; PHP handles the heavy data lifting. To help you build a more specific example, let me know:
Are you using a framework (like Laravel or Symfony) or Vanilla PHP?
Do you need to handle Server-Side Filtering (filtering via SQL) or client-side?
I can provide the exact SQL queries or API routes based on your choice!
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.
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.
Step 1: Install AG Grid
To get started, download the AG Grid library from the official website. For this example, we'll use the community edition.
1. Endpoint: /api/grid-data (GET)
<?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'] ?? [];
$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
]);
7. Complete Project Structure
Here’s a production-ready structure you can clone:
aggregrid-php-example/
├── config/
│ └── database.php
├── api/
│ └── get-rows.php
├── public/
│ └── index.html
├── composer.json (optional for autoloading)
└── README.md
composer.json (if you want to add logging or error handling): , params
"require":
"monolog/monolog": "^3.0"