Tuesday, October 20, 2009

Paging Grid with PHP and MySql

1. modify data.php

 $conn = mysql_connect("localhost", "root", "") or die (mysql_error ());
 $db = mysql_select_db ("extjs") or die (mysql_error ());
        $num_result = mysql_query ("SELECT * FROM strawhats") or die (mysql_error());         
        $totaldata = mysql_num_rows($num_result);
        $result=mysql_query ("SELECT * FROM strawhats ORDER BY id LIMIT ".$_POST['start'].", ".$_POST['limit']."") or die (mysql_error ()); 
$data = array();
 
 while ($row=mysql_fetch_object($result))
 {
  $data [] = $row;
 }

echo '({"total":"'.$totaldata.'","results":'.json_encode($data).'})';  
?>
 
2. modify db-grid.js ( rename it to paging-grid.js )
Ext.onReady(function(){
 
    // create the data store
    var store = new Ext.data.JsonStore({ 
totalProperty: 'total', // total data, see json output
  root: 'results', // see json output 
  url: 'data.php',    
        fields: [
           {name: 'id', type: 'int'},
     'name', 'position', 'ambition'
        ]
    }); 
store.load({params:{start: 0, limit: 10}});
 
// create the Grid
    var grid = new Ext.grid.GridPanel({
        store: store,
        columns: [
            {id:'id',header: "ID", width: 30, sortable: true, dataIndex: 'id'},
   {header: 'Name', width: 100, sortable: true, dataIndex: 'name'},
   {header: 'Position', width: 100, sortable: true, dataIndex: 'position'},
   {header: 'Ambition', width: 250, sortable: true, dataIndex: 'ambition'} 
        ],
        stripeRows: true,
        height:250,
        width:500,
        title:'Paging Grid' 
bbar: new Ext.PagingToolbar({
   pageSize: 25,
   store: store,
   displayInfo: true,
   displayMsg: 'Displaying topics {0} - {1} of {2}',
   emptyMsg: "No topics to display"   
  })
    });
 
 // render this grid to paging-grid element
    grid.render('paging-grid');
 
});
 
3. modify db-grid.html ( rename it to paging-grid.html )
<html>
 <head>
  <title>PAGING GRID EXAMPLE</title>
  
  <link rel="stylesheet" href="ext-2.2/resources/css/ext-all.css" />
 
  
  <script type="text/javascript" src="ext-2.2/adapter/ext/ext-base.js"></script>
 
  
  <script type="text/javascript" src="ext-2.2/ext-all.js"></script> 
 
  
  <script type="text/javascript" src="paging-grid.js"></script>
 </head> 
 <body>
 
  
  <div id="paging-grid"></div>
 
 </body>
</html> 

No comments: