Aggrid Php Example Updated //top\\

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

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.

AG Grid PHP Example

D. Handling AG Grid Request Models

  • Observation: AG Grid sends complex JSON objects for sorting and filtering.
  • Issue: PHP's

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: Building a robust data grid in PHP doesn't

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.


🧪 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]);

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. Observation: AG Grid sends complex JSON objects for

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

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 |

🧱 Tech Stack

  • Frontend: AG Grid (JavaScript) + Fetch API
  • Backend: PHP 8.2+ (Slim or vanilla PHP)
  • Database: MySQL / PostgreSQL
  • Security: Prepared statements, CORS, input validation

4. Sorting and Filtering

  • For small datasets (e.g., < 1,000 rows), you can let AG Grid handle sorting/filtering in the browser (Client-Side Model).
  • For large datasets, the PHP file must read the sortModel and filterModel sent by AG Grid's Server-Side Row Model. In the PHP example above, I implemented a simplified manual check for GET parameters to demonstrate how to hook into SQL ORDER BY clauses securely.

Prerequisites

  • PHP 7.2 or later
  • MySQL 5.7 or later
  • AG Grid Community Edition

© Software FX, Inc. All Rights Reserved. Chart FX, Grid FX & PowerGadgets are registered trademarks of Software FX, Inc. DataParts is a trademark of Software FX, Inc.

Citrix® and Citrix Xenapp™ are trademarks and registered trademarks of Citrix Systems, Inc.

All other names are trademakrs or registered trademarks of their respective owners.

Java and all Java-based marks are trademakrs or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.