Aggrid Php Example Updated May 2026
Use code with caution. π Key Features in this UpdateModern Initialization: Uses agGrid.createGrid(), replacing the older new agGrid.Grid() constructor.
Fetch API: Replaces jQuery AJAX for a dependency-free, native JavaScript experience.
Responsive Design: Uses the flex: 1 property in defaultColDef to ensure the grid fills the screen width.
Security: Uses PHP PDO to prevent SQL injection during data retrieval. π οΈ Advanced Optimizations
If you are working with millions of rows, consider these additions:
Server-Side Row Model: Instead of loading all data at once, use the serverSide model to fetch data chunks as the user scrolls.
CRUD Integration: Add event listeners like onCellValueChanged to send POST requests back to a PHP update.php script for real-time editing.
Export to Excel: AG Grid Enterprise allows you to export your filtered PHP data directly to .xlsx files.
Assuming you want a concise, up-to-date PHP example showing how to load data into AG Grid (frontend) and serve it from PHP (backend) via JSON β hereβs a minimal end-to-end snippet.
Frontend (index.html)
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>AG Grid PHP Example</title>
<script src="https://unpkg.com/ag-grid-community/dist/ag-grid-community.min.noStyle.js"></script>
<link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-grid.css" />
<link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-theme-alpine.css" />
<style>
html, body, #myGrid height: 100%; margin: 0; width: 100%;
</style>
</head>
<body>
<div id="myGrid" class="ag-theme-alpine"></div>
<script>
const columnDefs = [
field: "id", sortable: true, filter: true, width: 90 ,
field: "name", sortable: true, filter: true ,
field: "email", sortable: true, filter: true ,
field: "created_at", headerName: "Created", sortable: true, filter: true
];
const gridOptions =
columnDefs,
defaultColDef: resizable: true ,
pagination: true,
paginationPageSize: 20
;
const eGridDiv = document.querySelector('#myGrid');
new agGrid.Grid(eGridDiv, gridOptions);
// Fetch data from PHP endpoint
fetch('api/users.php')
.then(r =>
if (!r.ok) throw new Error('Network response was not ok');
return r.json();
)
.then(data => gridOptions.api.setRowData(data))
.catch(err => console.error('Fetch error:', err));
</script>
</body>
</html>
Backend (api/users.php)
<?php
header('Content-Type: application/json');
// Simple PDO connection β adjust DSN, user, pass for your environment
$dsn = 'mysql:host=127.0.0.1;dbname=mydb;charset=utf8mb4';
$user = 'dbuser';
$pass = 'dbpass';
try
$pdo = new PDO($dsn, $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
// Basic example: return all users. For large tables, implement paging/filtering server-side.
$stmt = $pdo->query('SELECT id, name, email, created_at FROM users ORDER BY id DESC LIMIT 500');
$rows = $stmt->fetchAll();
echo json_encode($rows);
catch (PDOException $e)
http_response_code(500);
echo json_encode(['error' => 'Database error']);
Notes / suggestions (concise)
Related search suggestions (useful terms)
Title: "Unlock the Power of Interactive Tables with AG Grid PHP Example"
Introduction:
Are you tired of using boring, static tables on your website? Do you want to provide your users with a more engaging and interactive experience? Look no further than AG Grid, a powerful and feature-rich JavaScript library for creating interactive tables. In this post, we'll explore how to use AG Grid with PHP to create a dynamic and customizable table.
What is AG Grid?
AG Grid is a popular JavaScript library for creating interactive tables. It offers a wide range of features, including:
Why Use AG Grid with PHP?
While AG Grid is a JavaScript library, it can be easily integrated with PHP to create a dynamic and interactive table. By using AG Grid with PHP, you can:
AG Grid PHP Example
In this example, we'll create a simple AG Grid table using PHP and MySQL. We'll assume that you have a basic understanding of PHP and MySQL.
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.
Step 2: Create a MySQL Database
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 | aggrid php example updated
Step 3: Create a PHP Script
Create a PHP script called "grid.php" and add the following code:
<?php
// Configuration
$dbHost = 'localhost';
$dbUsername = 'your_username';
$dbPassword = 'your_password';
$dbName = 'your_database';
// Connect to database
$conn = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
// Check connection
if ($conn->connect_error)
die("Connection failed: " . $conn->connect_error);
// Fetch data from database
$sql = "SELECT * FROM employees";
$result = $conn->query($sql);
// Close database connection
$conn->close();
// Convert data to JSON
$data = array();
while($row = $result->fetch_assoc())
$data[] = $row;
// Output JSON data
header('Content-Type: application/json');
echo json_encode($data);
This script connects to a MySQL database, fetches data from the "employees" table, and outputs the data in JSON format.
Step 4: Create an HTML File
Create an HTML file called "index.html" and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>AG Grid PHP Example</title>
<script src="https://unpkg.com/ag-grid-community/dist/ag-grid-community.min.noStyle.js"></script>
<link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-grid.css">
<link rel="stylesheet" href="https://unpkg.com/ag-grid-community/dist/styles/ag-theme-balham.css">
</head>
<body>
<div id="grid" style="height: 200px; width: 400px;" class="ag-theme-balham"></div>
<script>
// Fetch data from PHP script
fetch('grid.php')
.then(response => response.json())
.then(data =>
// Create AG Grid
const gridOptions =
columnDefs: [
field: 'name' ,
field: 'email' ,
field: 'department'
],
rowData: data
;
new agGrid.Grid(document.getElementById('grid'), gridOptions);
);
</script>
</body>
</html>
This HTML file includes the AG Grid library and creates a simple grid with three columns. It then fetches data from the "grid.php" script and passes it to the AG Grid.
Conclusion:
In this example, we've created a simple AG Grid table using PHP and MySQL. We've demonstrated how to fetch data from a database and display it in an interactive table. AG Grid offers a wide range of features and customization options, making it a powerful tool for creating dynamic and interactive tables.
I hope this helps! Let me know if you have any questions or need further clarification.
Here is an updated version with more recent information
Title: "AG Grid PHP Example: Create Interactive Tables with PHP and MySQL"
Introduction:
AG Grid is a powerful and feature-rich JavaScript library for creating interactive tables. In this post, we'll explore how to use AG Grid with PHP and MySQL to create a dynamic and customizable table.
What is AG Grid?
AG Grid is a popular JavaScript library for creating interactive tables. It offers a wide range of features, including:
Why Use AG Grid with PHP?
While AG Grid is a JavaScript library, it can be easily integrated with PHP to create a dynamic and interactive table. By using AG Grid with PHP, you can:
AG Grid PHP Example
In this example, we'll create a simple AG Grid table using PHP and MySQL. We'll assume that you have a basic understanding of PHP and MySQL.
We need a PHP script that acts as an API. AG Grid sends requests via POST (especially for the Row Model or when updating data).
File: api.php
This script handles two actions:
<?php
// api.php
header("Content-Type: application/json; charset=UTF-8");
// Database Configuration
$host = 'localhost';
$db = 'test_db';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try
$pdo = new PDO($dsn, $user, $pass, $options);
catch (\PDOException $e)
echo json_encode(["error" => $e->getMessage()]);
exit;
// Determine Action based on GET param (or use POST data parsing for stricter APIs)
$action = $_GET['action'] ?? 'fetch';
// 1. HANDLE DATA FETCHING
if ($action === 'fetch')
// Basic SQL
$sql = "SELECT * FROM employees";
$where = [];
$params = [];
// --- FILTERING (Simple Implementation) ---
// AG Grid Filter Model is usually sent via POST or GET depending on config.
// Here we check for simple query params for demonstration:
if (isset($_GET['department']) && !empty($_GET['department']))
$where[] = "department = ?";
$params[] = $_GET['department'];
if (count($where) > 0)
$sql .= " WHERE " . implode(" AND ", $where);
// --- SORTING ---
// AG Grid sends sortModel: [colId: "salary", sort: "asc"]
// We simulate sorting via GET params for this example:
if (isset($_GET['sortCol']) && isset($_GET['sortDir']))
// Validate sortDir to prevent SQL injection
$dir = strtoupper($_GET['sortDir']) === 'DESC' ? 'DESC' : 'ASC';
// Whitelist columns to prevent SQL injection
$allowedCols = ['employee_name', 'salary', 'department'];
if (in_array($_GET['sortCol'], $allowedCols))
$sql .= " ORDER BY " . $_GET['sortCol'] . " " . $dir;
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$data = $stmt->fetchAll();
echo json_encode($data);
// 2. HANDLE ROW UPDATE
elseif ($action === 'update')
// Read raw POST data (JSON)
$input = json_decode(file_get_contents('php://input'), true);
if (!$input
Create a table products to demonstrate dynamic data updates.
CREATE DATABASE aggrid_demo; USE aggrid_demo;CREATE TABLE products ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, category VARCHAR(100), price DECIMAL(10,2), stock INT DEFAULT 0, last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP );
INSERT INTO products (name, category, price, stock) VALUES ('Laptop Pro', 'Electronics', 1299.99, 25), ('Wireless Mouse', 'Accessories', 29.99, 150), ('Mechanical Keyboard', 'Accessories', 89.50, 75), ('USB-C Hub', 'Cables', 45.00, 40), ('Monitor 27"', 'Electronics', 299.99, 12);
If your dataset grows beyond 20,000 rows, Client-Side rendering will slow down the browser. You should upgrade the implementation to use AG Grid's Server-Side Row Model (SSRM): // Column Definitions const columnDefs = [ field:
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!
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:
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
Integrating typically involves a frontend client (JavaScript) requesting data from a backend script (PHP) that queries a database (like MySQL). In modern versions like AG Grid 33 , the process is streamlined by utilizing the createGrid API and the Server-Side Row Model (SSRM) for large datasets. 1. Frontend: The JavaScript Grid The grid requires a container and a configuration object ( gridOptions ). For large datasets, use rowModelType: 'serverSide' to fetch only the data needed for the current view. "height: 500px;" "ag-theme-alpine"
"https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js" > const gridOptions = columnDefs: [ field: 'agNumberColumnFilter' , field: 'agTextColumnFilter' , field:
], // For large datasets (Requires AG Grid Enterprise) rowModelType: 'serverSide' , pagination: true, paginationPageSize: ;
const myGridElement = document.querySelector(
); const api = agGrid.createGrid(myGridElement, gridOptions);
// Define how to fetch data from your PHP backend const datasource = getRows: (params) => fetch( 'backend.php' , method:
, 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(() => params.fail()); ;
api.setGridOption( 'serverSideDatasource' , datasource); </ Use code with caution. Copied to clipboard createGrid
is the updated method for instantiating grids in recent versions. 2. Backend: The PHP Script ( backend.php
The backend script receives a JSON request containing sorting, filtering, and row range ( $start = $request[ 'startRow' ; $limit = ($request[ ) - $start; // Example Database Connection (PDO) "mysql:host=localhost;dbname=test"
// Build dynamic SQL based on AG Grid request (simplified for example) "SELECT * FROM users LIMIT :start, :limit" ; $stmt = $pdo->prepare($sql); $stmt->bindValue( , (int)$start, PDO::PARAM_INT); $stmt->bindValue(
, (int)$limit, PDO::PARAM_INT); $stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); $total = $pdo->query( "SELECT COUNT(*) FROM users" )->fetchColumn(); json_encode([ => (int)$total ]); Use code with caution. Copied to clipboard 3. Key Framework Integrations
If you are using a modern PHP framework, there are pre-built adapters to handle the complex SQL generation for sorting and grouping: ag-grid-laravel adapter to automatically handle AgGridQueryBuilder contributed module exists for integrating AG Grid into Drupal views. 4. Implementation Best Practices
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?
This updated AG Grid PHP example provides a fully functional, enterprise-ready data grid with server-side sorting, filtering, pagination, and CRUD operations. The backend uses modern PHP (8.1+) with PDO, and the frontend leverages AG Grid v31βs server-side row model for optimal performance even with thousands of rows.
Next steps: Integrate AG Grid Enterprise features like Excel export, charting, or master/detail views, and enhance PHP with input validation, logging, and rate limiting for production deployment.
File structure recap:
aggrid-php-example/
βββ index.html
βββ server.php
βββ db.php
βββ (optional) .env for credentials
Run with php -S localhost:8000 and open http://localhost:8000. Your AG Grid will communicate seamlessly with the PHP backend, handling all dynamic data operations in real time.
Integrating requires a bridge between your backend (MySQL/PostgreSQL) and the frontend grid via a JSON API. Because AG Grid is a client-side JavaScript library, the PHP portion focuses on serving data and handling server-side operations like pagination, filtering, and sorting. 1. Basic Project Structure
A modern AG Grid setup typically uses a "Fetch" pattern rather than direct PHP embedding: index.html : Loads the AG Grid library and initializes the grid. : Handles the gridOptions and fetches data from the backend. : Queries the database and returns a JSON-encoded array. 2. Frontend Setup (JavaScript)
To initialize the grid, you need to define column headers and a source. Using the latest setGridOption method is recommended for updates. javascript gridOptions = { columnDefs: [ field: , headerName: , field: , headerName: "Full Name" , field: , headerName: , sortable: // Use pagination for large datasets pagination: , paginationPageSize: // Initialize and Fetch Data gridDiv = document.querySelector( gridApi = agGrid.createGrid(gridDiv, gridOptions);
fetch( 'data.php'
) .then(response => response.json()) .then(data => gridApi.setGridOption( Use code with caution. Copied to clipboard 3. Backend Data Source (PHP) script serves as the API. Ensure you set the correct Content-Type header so the browser interprets it as JSON. query( "SELECT id, name, email FROM users" ); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); // Output JSON for AG Grid json_encode($results); (PDOException $e) json_encode([ => $e->getMessage()]); ?> Use code with caution. Copied to clipboard 4. Advanced: Server-Side Row Model For datasets with millions of rows, use the AG Grid Enterprise Server-Side Row Model
: Instead of fetching all data at once, the grid sends a request to PHP containing the start row, end row, sort parameters, and filters. PHP Handling : Use these parameters to construct a SQL query to return only the visible slice of data. 5. Key Updates for 2026 Modularization
: AG Grid v33+ uses a modular system to reduce bundle size by 20-40%. : Use the new Theming API
for deeper CSS customization without overriding complex internal rules. Browser Support
: AG Grid 27+ has officially dropped support for Internet Explorer 11. AG Grid Blog CRUD example
(Create, Read, Update, Delete) showing how to send edits back to a PHP script? solidjs-community/solid-ag-grid - GitHub
Here are some of the features that make AG Grid stand out: * Grouping / Aggregation * * Accessibility support. * Custom Filtering. What's New in AG Grid 33
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
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. Backend (api/users
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
While AG Grid is primarily a JavaScript-based library, it is commonly integrated with PHP backends to handle server-side data processing like filtering, grouping, and pagination. Updated AG Grid & PHP Integration
Modern implementations focus on using the Server-Side Row Model (SSRM) to fetch data from a PHP RESTful API.
Server-Side Logic: Your PHP script (often using frameworks like Laravel) receives a JSON request containing the grid's state (sorting, filtering, row groups) and returns a formatted JSON response containing the data and total row count.
Data Updates: You can track changes in the grid using the onCellValueChanged event to identify and send only modified rows back to your PHP backend for saving.
Performance: AG Grid uses row and column virtualization to maintain high performance even when handling millions of rows processed via your PHP server. Key Implementation Resources
Official Blog Guide: The AG Grid Blog provides a detailed walkthrough for setting up the Server-Side Row Model with Laravel and MySQL, which is the most "updated" standard for modern PHP development.
CRUD Application Patterns: For a more general approach, developers often follow a multi-part series on building CRUD applications where the "Middle Tier" is a PHP-based REST service.
Theming and UI: Recent updates (v33+) have introduced a new Theming API that makes it easier to style your grid to match your PHP application's design without deep CSS overrides. Notable "Interesting Paper" Context
While no formal academic "paper" is the primary source for this setup, the "Core Philosophy" documentation and the technical deep-dives on the AG Grid Github function as the authoritative technical references for these integrations.
Using AG Grid Server-Side row model with Angular, Laravel & MySQL
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:
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)
Since you haven't pasted the specific code you are working on, I have drafted a generic code review based on the common architecture of an AG Grid integrated with a PHP backend.
This review assumes a standard setup: a PHP script returning JSON data (Server-Side) or a PHP file rendering the HTML/JS (Client-Side).
You can use this as a checklist to review your own code, or paste your code in the next message for a specific review.
AG Grid is one of the most powerful JavaScript data grids available today. When combined with a PHP backend, it becomes an enterprise-grade solution for displaying, filtering, sorting, and paginating large datasets. This updated example demonstrates how to integrate AG Grid with a modern PHP backend (using MySQL/MariaDB) while leveraging the latest features of both technologies.
Build a high-performance AG Grid using PHP backend to handle large datasets with server-side pagination, sorting, and filtering.