Aggrid Php Example Updated May 2026

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.

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

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.


Shopping Basket