Aggrid Php Example Updated !!install!! May 2026

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.

10. Conclusion

This updated AG Grid PHP example gives you a robust, secure, and scalable foundation for integrating AG Grid with a modern PHP backend. You can now handle millions of rows with real-time filtering, sorting, and pagination—without bogging down the client’s browser.

Key takeaways:

Next steps:


References:

Need help? Copy the code above, adjust your database credentials, and you’ll have an enterprise-grade datagrid running in under 30 minutes. This is the most current and detailed AG Grid PHP example available online as of 2025.


Last updated: January 2025 – Compatible with AG Grid v31.3+, PHP 8.2/8.3, and MySQL 8.0.

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


4. Building the PHP API Endpoint (Updated)

Create api/get-rows.php. This is the core updated AG Grid PHP example.

Key updates from old tutorials:

<?php
// api/get-rows.php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(0);

require_once '../config/database.php';

$input = json_decode(file_get_contents('php://input'), true);

$startRow = (int)($input['startRow'] ?? 0); $endRow = (int)($input['endRow'] ?? 20); $limit = $endRow - $startRow; $offset = $startRow;

$sortModel = $input['sortModel'] ?? []; $filterModel = $input['filterModel'] ?? [];

$pdo = getConnection();

// ---------- Build WHERE clause dynamically ---------- $whereClause = ""; $params = [];

foreach ($filterModel as $colId => $filter) AG Grid PHP Example: A Complete, Updated Implementation

// ---------- Build ORDER BY clause ---------- $orderClause = ""; if (!empty($sortModel)) $sorts = []; foreach ($sortModel as $sort) $col = $sort['colId']; $dir = strtoupper($sort['sort']) === 'ASC' ? 'ASC' : 'DESC'; $sorts[] = "$col $dir"; $orderClause = " ORDER BY " . implode(", ", $sorts);

// ---------- Get total row count (for lastRow) ---------- $countSql = "SELECT COUNT(*) FROM products WHERE 1=1 $whereClause"; $countStmt = $pdo->prepare($countSql); foreach ($params as $key => $val) $countStmt->bindValue($key, $val); $countStmt->execute(); $totalRows = (int)$countStmt->fetchColumn();

// ---------- Get paginated data ---------- $sql = "SELECT id, product_name, category, price, stock_quantity, last_updated FROM products WHERE 1=1 $whereClause $orderClause LIMIT :limit OFFSET :offset";

$stmt = $pdo->prepare($sql);

// Bind filter params foreach ($params as $key => $val) $stmt->bindValue($key, $val); $stmt->bindValue(':limit', $limit, PDO::PARAM_INT); $stmt->bindValue(':offset', $offset, PDO::PARAM_INT); $stmt->execute();

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Return AG Grid expected structure echo json_encode([ 'rows' => $rows, 'lastRow' => $totalRows ]);

database.php (config file):

<?php
// config/database.php
function getConnection() 
    $host = 'localhost';
    $db = 'your_database';
    $user = 'your_user';
    $pass = 'your_password';
    $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,
];
return new PDO($dsn, $user, $pass, $options);


Part 1: The Database Setup

Let’s define a simple dataset to manipulate. Run this SQL in your database:

CREATE TABLE employees (
    id INT AUTO_INCREMENT PRIMARY KEY,
    employee_name VARCHAR(100),
    job_title VARCHAR(100),
    department VARCHAR(50),
    salary INT
);
INSERT INTO employees (employee_name, job_title, department, salary) VALUES
('Alice Johnson', 'Software Engineer', 'Engineering', 95000),
('Bob Smith', 'Project Manager', 'Operations', 85000),
('Charlie Davis', 'UX Designer', 'Product', 78000),
('Diana Evans', 'Data Analyst', 'Marketing', 72000);

1. Why an Updated PHP Example is Necessary

AG Grid evolves quickly. The old ways of dumping 10,000 rows to the client and letting the grid filter them no longer work for modern applications.

Old approach (deprecated):

Updated approach (this tutorial):

This updated PHP example uses the Server-Side Row Model, which is now the standard for enterprise-level grids.


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')  !isset($input['id'])) 
        echo json_encode(["success" => false, "message" => "Invalid data"]);
        exit;
// Dynamic update builder (only update provided fields)
    $fields = [];
    $params = [];
// Whitelist allowed columns to update
    $allowed = ['employee_name', 'job_title', 'department', 'salary'];
foreach ($input as $key => $value) 
        if (in_array($key, $allowed)) 
            $fields[] = "$key = ?";
            $params[] = $value;
if (count($fields) > 0) 
        $params[] = $input['id']; // ID for WHERE clause
        $sql = "UPDATE employees SET " . implode(", ", $fields) . " WHERE id = ?";
try 
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            echo json_encode(["success" => true]);
         catch (Exception $e) 
            echo json_encode(["success" => false, "message" => $e->getMessage()]);
else 
        echo json_encode(["success" => true, "message" => "No changes detected"]);