Example - Quick

Example - Quick – Quickly retrieve data from a database table

Description

Binding an SQL query

To retrieve the data that the datagrid will display you can begin by passing a simple SQL statement to the bind() method.

Using an SQL query as datasource

<?php
require 'Structures/DataGrid.php';

// Instantiate the DataGrid
$datagrid =& new Structures_DataGrid();

// Setup your database connection
$options = array('dsn' => 'mysql://user:password@host/db_name');

// Bind a basic SQL statement as datasource
$test $datagrid->bind('SELECT * FROM my_table'$options);

// Print binding error if any
if (PEAR::isError($test)) {
    echo 
$test->getMessage(); 
}

// Print the DataGrid with the default renderer (HTML Table)
$test $datagrid->render();

// Print rendering error if any
if (PEAR::isError($test)) {
    echo 
$test->getMessage(); 
}

?>

If you are familiar with the SQL language you'll certainly find many ways to adapt the above example to your needs, using more complex queries.

You can also page through your dataset with the automatic paging feature as shown below. This feature transparently adds LIMIT clauses to your SQL statement, providing optimized database access.

Automatic paging

<?php
require 'Structures/DataGrid.php';

// 10 records per page
$datagrid =& new Structures_DataGrid(10);

// Setup your datasource
$options = array('dsn' => 'mysql://user:password@host/db_name');
$test $datagrid->bind("SELECT * FROM my_table"$options);
if (
PEAR::isError($test)) {
    echo 
$test->getMessage(); 
}

// Print the DataGrid with the default renderer (HTML Table)
$test $datagrid->render();
if (
PEAR::isError($test)) {
    echo 
$test->getMessage(); 
}

// Print the HTML paging links
$test $datagrid->render(DATAGRID_RENDER_PAGER);
if (
PEAR::isError($test)) {
    echo 
$test->getMessage(); 
}

?>
What can I do with the column formatter? (Previous) How to build a datagrid using many of the features (Next)
Last updated: Sat, 16 Feb 2019 — Download Documentation
Do you think that something on this page is wrong? Please file a bug report.
View this page in:
  • English

User Notes:

Note by: doconnor
It's worth looking at the <a href="http://pear.php.net/manual/en/package.structures.structures-datagrid.rendering.php">rendering the output</a> section too.

You can change the default renderer with setRenderer()