Tuesday, October 20, 2009

Building Grid with Json data store

1. Create the table first dan insert some sample data
CREATE TABLE IF NOT EXISTS `strawhats` (
`id` TINYINT(4) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(25) NOT NULL,
`POSITION` VARCHAR(25) NOT NULL,
`ambition` TEXT NOT NULL,
PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
 
INSERT INTO `strawhats` (`id`, `name`, `POSITION`, `ambition`) VALUES
(1, ‘Monkey D Luffy’, ‘Captain’, ‘I Will become the pirate king’),
(2, ‘Roronoa zoro’, ‘Swordman’, ‘Become greatet swordman’),
(3, ‘Sanji’, ‘Cook’, ‘Find all blue’),
(4, ‘Nami’, ‘Navigator’, ‘Draw map of the world’),
(5, ‘Usopp’, ‘Sniper’, ‘Become greatest warrior’);

2. db-grid.html
<html>
 <head>
  <title>DB GRID SAMPLE</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="db-grid.js"></script>
 </head>
 <body>
 
  
  <div id="db-grid"></div> 
 </body>
</html>
 
3. db-grid.js
Ext.onReady(function(){
 
 // create the data store
 var store = new Ext.data.JsonStore({
  url: ‘data.php,
  fields: [
   {name: ‘id’, type: ‘int’},name, ‘position’, ‘ambition’
  ]
 });
 
 // load data from the url ( data.php )
 store.load();
 
 // 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:’DB Grid’
 });
 
 // render grid
 grid.render(’db-grid’);
 
}); 
 
4. data.php
the result of this code is the data form database in json format

 $conn = mysql_connect(”localhost”, “root”, “”) or die (mysql_error ());
 $db = mysql_select_db (”extjs”) or die (mysql_error ());
 
 $result=mysql_query (”SELECT * FROM strawhats”) or die (mysql_error ());
 
 $data = array();
 
 while ($row=mysql_fetch_object($result))
 {
  $data [] = $row;
 }
 
 echo json_encode($data);
?>

 

No comments: