Aggrid Php Example Updated -
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:
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.
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
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 |
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. aggrid php example updated
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.
AG Grid’s server-side row model requires specific request parameters. We’ll build a RESTful endpoint that handles:
File: db.php (PDO connection)
<?php header('Content-Type: application/json'); header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE'); header('Access-Control-Allow-Headers: Content-Type');$host = 'localhost'; $dbname = 'aggrid_demo'; $user = 'root'; $pass = '';
try $pdo = new PDO("mysql:host=$host;dbname=$dbname;charset=utf8mb4", $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); catch(PDOException $e) die(json_encode(['error' => 'Database connection failed'])); ?>
File: server.php (main API logic)
<?php require_once 'db.php';$request_method = $_SERVER['REQUEST_METHOD']; $input = json_decode(file_get_contents('php://input'), true);
// Handle GET request for grid data if ($request_method === 'GET' && isset($_GET['action']) && $_GET['action'] === 'getRows') // Extract AG Grid request parameters $startRow = isset($_GET['startRow']) ? (int)$_GET['startRow'] : 0; $endRow = isset($_GET['endRow']) ? (int)$_GET['endRow'] : 100; $limit = $endRow - $startRow;
$sortModel = isset($_GET['sortModel']) ? json_decode($_GET['sortModel'], true) : []; $filterModel = isset($_GET['filterModel']) ? json_decode($_GET['filterModel'], true) : []; // Base query $sql = "SELECT * FROM products"; $countSql = "SELECT COUNT(*) as total FROM products"; $params = []; // Build WHERE clause from filterModel $whereClauses = []; if (!empty($filterModel)) foreach ($filterModel as $field => $filter) if ($filter['filterType'] === 'text') $whereClauses[] = "$field LIKE :$field"; $params[":$field"] = '%' . $filter['filter'] . '%'; elseif ($filter['filterType'] === 'number') if (isset($filter['filter'])) $whereClauses[] = "$field = :$field_eq"; $params[":$field_eq"] = $filter['filter']; if (isset($filter['filterTo'])) $whereClauses[] = "$field <= :$field_to"; $params[":$field_to"] = $filter['filterTo']; if (!empty($whereClauses)) $whereStr = " WHERE " . implode(" AND ", $whereClauses); $sql .= $whereStr; $countSql .= $whereStr; // Build ORDER BY from sortModel if (!empty($sortModel)) $orderBy = []; foreach ($sortModel as $sort) $orderBy[] = "$sort['colId'] $sort['sort']"; $sql .= " ORDER BY " . implode(", ", $orderBy); // Add LIMIT for pagination $sql .= " LIMIT $startRow, $limit"; // Get total row count (without pagination) $totalStmt = $pdo->prepare($countSql); foreach ($params as $key => &$val) $totalStmt->bindParam($key, $val); $totalStmt->execute(); $totalRows = $totalStmt->fetch(PDO::FETCH_ASSOC)['total']; // Get paginated data $stmt = $pdo->prepare($sql); foreach ($params as $key => &$val) $stmt->bindParam($key, $val); $stmt->execute(); $rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // Return AG Grid expected format echo json_encode([ 'success' => true, 'rows' => $rows, 'lastRow' => $totalRows ]); exit;// Handle POST to add a new row if ($request_method === 'POST' && isset($_GET['action']) && $_GET['action'] === 'addRow') $stmt = $pdo->prepare("INSERT INTO products (name, category, price, stock) VALUES (:name, :category, :price, :stock)"); $stmt->execute([ ':name' => $input['name'], ':category' => $input['category'], ':price' => $input['price'], ':stock' => $input['stock'] ]); echo json_encode(['success' => true, 'id' => $pdo->lastInsertId()]); exit;
// Handle PUT to update a row if ($request_method === 'PUT' && isset($_GET['action']) && $_GET['action'] === 'updateRow') $stmt = $pdo->prepare("UPDATE products SET name=:name, category=:category, price=:price, stock=:stock WHERE id=:id"); $stmt->execute([ ':id' => $input['id'], ':name' => $input['name'], ':category' => $input['category'], ':price' => $input['price'], ':stock' => $input['stock'] ]); echo json_encode(['success' => true]); exit;
// Handle DELETE if ($request_method === 'DELETE' && isset($_GET['action']) && $_GET['action'] === 'deleteRow') $id = $_GET['id']; $stmt = $pdo->prepare("DELETE FROM products WHERE id = ?"); $stmt->execute([$id]); echo json_encode(['success' => true]); exit; ?>
Build a high-performance AG Grid using PHP backend to handle large datasets with server-side pagination, sorting, and filtering. Integrating AG Grid with PHP is a powerful
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 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
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)
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.
Integrating AG Grid with a Modern PHP Backend
If you’re looking for an updated AG Grid PHP example, you’ve likely discovered that most tutorials online are outdated. They still use mysql_* functions, ignore prepared statements, or fail to handle AG Grid’s full filtering, sorting, and pagination capabilities. ], // For large datasets (Requires AG Grid
This guide provides a modern, production-ready integration between AG Grid (v31+) and PHP 8.2+ using:
By the end, you’ll have a fully functional, high-performance datagrid that sorts, filters, and paginates directly through SQL queries triggered by your PHP backend.