Aggrid Php Example Updated «2026 Edition»

AG Grid PHP Example: A Complete, Updated Implementation

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.

2. The Good (What works)

  • Data Structure: The JSON output generally matches AG Grid's expected structure (an array of objects).
  • Separation of Concerns: Using a dedicated PHP endpoint for data fetching keeps the frontend logic clean.

Part 2: The Backend (PHP)

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:

  1. Fetch Data: Reads parameters for sorting and filtering.
  2. Update Data: Accepts a single row edit and updates the database.
<?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') 

B. Performance: Pagination vs. Full Load

  • Observation: Does the example load the entire dataset at once?
  • Issue: AG Grid is capable of handling hundreds of thousands of rows via Server-Side Row Model or Infinite Scroll. Fetching all rows in PHP (SELECT * FROM table) will crash the browser or timeout PHP for large datasets.
  • Recommendation: Implement server-side pagination. The PHP script should interpret startRow and endRow from the AG Grid request and append LIMIT clauses to the SQL query.

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.

Next Steps for Scalability

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):

  1. Frontend: Change rowModelType: 'serverSide'.
  2. Backend: Update api.php to parse complex AG Grid JSON requests:
    // AG Grid sends this via POST for SSRM
    "startRow": 0, 
      "endRow": 100, 
      "sortModel": ["colId": "salary", "sort": "asc"],
      "filterModel": ...
    
  3. SQL: Implement LIMIT :startRow, :endRow in your SQL query to paginate results.

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)

  • For large datasets use server-side row model or implement paging, sorting, filtering server-side.
  • Sanitize and validate parameters if you add query params (page, sort, filter).
  • Serve via HTTPS in production.
  • If you need AG Grid enterprise features, include the enterprise bundle and license.

Related search suggestions (useful terms)

  • "ag-grid php example"
  • "ag-grid server side pagination php"
  • "ag-grid backend sorting filtering php"

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)  strpos($row['email'], $filter) !== false
// 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

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); aggrid php example updated

$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?


User Management Portal

Use code with caution. 🚀 Key Features in this Update

Modern 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.

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()); ; AG Grid PHP Example: A Complete, Updated Implementation

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

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

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.


🧪 CRUD Update Example (PHP)

// PUT /api/user/id
$data = json_decode(file_get_contents('php://input'), true);
$stmt = $pdo->prepare("UPDATE users SET name = ?, email = ? WHERE id = ?");
$stmt->execute([$data['name'], $data['email'], $id]);
echo json_encode(['success' => true]);

5. Implementing Sorting, Filtering & Pagination

The example above automatically handles:

  • Sorting – Click column headers; sortModel is sent to PHP.
  • Filtering – Text/number filters trigger filterModel request.
  • Pagination – Uses startRow/endRow with cacheBlockSize.

Important update: AG Grid v31+ uses serverSideStoreType: 'partial' (replaces old serverSideStoreType: 'full'). Data Structure: The JSON output generally matches AG