Thursday, December 03, 2009

Cara hapus temp dbf file di Oracle

Di oracle di kenal juga temporary dbf file, kadang kala temporary database file tersebut sangat besar size nya dan musti kita reset biar tidak terlalu membebani size hardisk

Cara untuk menghapus temporary database file di oracle adalah :

SQL> ALTER DATABASE TEMPFILE '/u02/oradata/TESTDB/temp01.dbf' DROP INCLUDING DATAFILES;

Perintah di atas di gunakan untuk menghapus temp file dbf yang ada di oracle, tapi ini masih belum selesai, di mana di oracle tetap memerlukan temporary dbf file ini jadi kita perlu membuat temp dbf file yang baru. Scriptnya yaitu:

SQL> ALTER TABLESPACE temp ADD TEMPFILE '/u02/oradata/TESTDB/temp01.dbf' SIZE 512m
2 AUTOEXTEND ON NEXT 250m MAXSIZE UNLIMITED;

Di script di atas kita membuat temp dbf file baru dengan size 512mb dan size maksimal unlimited.

Understanding Flex itemEditors – Part 1: Inline itemEditors

Understanding Flex itemEditors – Part 1: Inline itemEditors

I recently completed a series on itemRenderers ― customizations to list controls that format the display of the list contents. Displaying and rendering content is a very effective UI technique and with Flex you can do nearly anything you can imagine.

This is Part 1 of a new series covering itemEditors, which allow data to be changed directly inside of a list control. This first article covers inline itemEditors, which are very simple, though quite useful, components you write directly inside your MXML files. Later articles in the series will cover more complex editing, validation, events, and using itemRenderers as itemEditors.
Requirements

Prerequisites:

Prior experience working with Flex Builder to create applications is needed.
The TextInput editor

Editing directly in list controls is convenient. Imagine a DataGrid of warehouse inventory where you can adjust the content right in the grid without needing a special pop-up (see Figure 1). The list controls have a built in editor, a TextInput control, that appears whenever the user clicks in an editable area, either a row (for a List), a branch (for a Tree), or a cell (for a DataGrid). All you need to do is set the list control's editable property to true. For a DataGrid you can exclude a column from being edited by setting the DataGridColumn's editable property to false.

itemEditors allow editing directly within a DataGrid

Figure 1. itemEditors allow editing directly within a DataGrid

itemEditors differ from itemRenderers in that only one instance of the itemEditor is seen, just on the cell being edited. The itemEditor is not seen until the cell to be edited receives input focus. Then the itemRenderer is hidden and the itemEditor is moved to that position, sized to fit the area, and given the data for the record. When editing is finished (by moving focus to another location), the list control copies the new value from the editor to the dataProvider record.

In the application shown in Figure 1, when the user clicks in a cell of the "Part #" column, the dataProvider[row][dataField] value is given to the text property of the itemEditor (TextInput) control. When editing is finished, the text property value from the itemEditor (TextInput) control is copied to the dataProvider[row][dataField]. The dataProvider, being a collection, dispatches an event in response to the update.

While the default TextInput control makes a fine editor, it really only works for the most simple of cases. It works fine for String values, for example, such as a book title, author name, or product number. If you need more control or want to validate the user's input, then you need to take matters into your own hands.
Flex Controls as itemEditors

Here is how you make an itemEditor which only accepts numeric values:















The restrict and maxChars properties ensure that age values are constrained to three-digit numbers.

The CheckBox is another common control to use for an itemEditor, because it is useful for editing Boolean values. Figure 2 shows an example of using the CheckBox to edit the values for an "In Stock" column of an inventory program.

Using a CheckBox as an itemEditor for a Boolean value

Figure 2. Using a CheckBox as an itemEditor for a Boolean value

Here is the code to make it work:










In this example the content of the cells in this column are rendered using a labelFunction (inStockLabeler), which can display descriptive strings such as "Yes", "No", "In Stock", or "Out of Stock". The itemEditor property is set to the mx.controls.CheckBox class. And there is another, equally important, property set on the DataGridColumn: editorDataField. This field indicates the property of the itemEditor class to use to fetch the value when editing is finished. In this case it is the CheckBox's selected property. When editing is finished, the DataGrid will use the CheckBox's selected property to replace the inStock property in the data record.

At this point, you may wonder why the example with the TextInput did not supply the editorDataField property. That is because the default value for editorDataField is "text" which just happens to be the name of the property on the TextInput control holding the value.

You can use this same technique with a number of Flex controls. Here is one for an order quantity column using NumericStepper, as shown in Figure 3:










Using a NumericStepper to edit quantities

Figure 3. Using a NumericStepper to edit quantities

Notice the editorDataField is "value" - the property of the NumericStepper that holds the current value of the control. Make sure you use the fully-qualified class name for the itemEditor property or else the compiler will not be able to find the class and flag the line with an error.
A more complex editor

Now suppose you want to do something a little more complex that doesn't have a ready-made Flex control available. Here is one which allows the user to enter a credit card number using four separate four-digit fields (see Figure 4):

Figure 4. Editing a credit card number in four separate fields

Here is the code to make it work:






















This inline itemEditor follows the same rules as other itemEditors and names the editorDataField as "value". The component chosen for the itemEditor is the HBox, which does not have a "value" property. To make this itemEditor work, a getter function named value is created to return the concatenation of the four input fields. Now when the user is finished editing the cell, the DataGrid can call upon the value property of the itemEditor and it will receive the combined fields.

Note the super.data = value in the data setter function. The data property - really the data getter function - is used extensively behind the scenes in the List controls and elsewhere in the framework (not to mention your own code). If you don't set the internal value of data using super.data, then the data getter function will return a null value and, most likely, cause your application to crash.

You can also see that I have overridden the data setter function. In that function I split up the credit card number among the four TextInput fields. This is the technique used to display the data to be edited. The editorDataField is the property used to retrieve the new value.

Thursday, November 05, 2009

Convert int to String (C#)

Cara untuk convert Integer to String :

const int AbsoluteZero = -273;
lblOut.Text = Convert.ToString(AbsoluteZero);

Tuesday, November 03, 2009

Membuat Sort Pada Jtable

Sebelum Sorting

Setelah Sorting




package test;

import java.awt.BorderLayout;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableRowSorter;

/**
 * @author echo
 */
public class SortedTable extends javax.swing.JFrame {

    /**
     * Serial Verion UID
     */
    private static final long serialVersionUID = -2093871956519605230L;

    private JScrollPane scrollpaneTable;

    private JTable tableData;

    private DefaultTableModel modelTabel;

    /**
     * Metode utama
     *
     * @param args
     * parameter comand line atau shell
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                SortedTable inst = new SortedTable();
                inst.setLocationRelativeTo(null);
                inst.setVisible(true);
            }
        });
    }

    /**
     * Membuat SortedTable baru
     */
    public SortedTable() {
        super();
        initGUI();
    }

    /**
     * Metode ini digunakan untuk pendeklarasian seluruh komponen GUI yang
     * berinteraksi dengan Frame
     */
    private void initGUI() {
        try {
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            getContentPane().add(getScrollpaneTable(), BorderLayout.CENTER);
            pack();
            this.setSize(485, 395);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * Metode ini digunakan untuk mendeklarasikan scrollpane tabel
     *
     * @return JScrollPane scrollpane table
     */
    private JScrollPane getScrollpaneTable() {
        if (scrollpaneTable == null) {
            scrollpaneTable = new JScrollPane();
            scrollpaneTable.setViewportView(getTableData());
        }
        return scrollpaneTable;
    }

    /**
     * Metode ini digunakan untuk mendeklarasikan tabel data
     *
     * @return JTable tabel data
     */
    private JTable getTableData() {
        if (tableData == null) {
            tableData = new JTable(getModelTable());
            tableData.setRowSorter(new TableRowSorter(getModelTable()));
        }
        return tableData;
    }

    /**
     * Metode ini digunakan untuk mendeklarasikan TableModel
     *
     * @return DefaultTableModel model
     */
    private DefaultTableModel getModelTable() {
        if (modelTabel == null) {
            Object[][] row = new Object[][]{
                {
                    "NetBeans", "Sun Microsystem"
                }, {
                    "Eclipse", "IBM"
                }, {
                    "Visual J#", "Microsoft"
                }, {
                    "JBuilder", "Bordland"
                }
            };
            Object[] colum = new Object[]{
                "Project", "Vendor"
            };
            modelTabel = new DefaultTableModel(row, colum){
//Untuk  readonly cell
 public boolean isCellEditable(int rowIndex, int columnIndex) {
                return false;
            }
 
};
        }
        return modelTabel;
    }
}

Friday, October 23, 2009

Cara Buat Kentang Goreng (French Fries)

Ada dua cara buat Kentang Goreng:
Cara yang Pertama:
  • Pertama: Potong2 kentang kecil sesuai ukuran (dikira kira),
    kentang dipotong kecil
    Kentang dipotong Kecil kecil
  • Rebus kentang setengah matang (kasih garam sedikit biar lebih gurih ya)
    Kentang direbus Setengah Matang
    Kentang direbus Setengah Matang
  • Angkat kentang lalu tiriskan selama 15-20 menit
    Kentang ditiriskan 15 - 20  Menit
    Kentang ditiriskan 15 - 20 Menit
  • Siapkan tepung beras + soda kue (baking powder /soda 2 sendok teh kira kira), lalu campur keduanya (takaran menyesuaikan aja)
    Campur Tepung Beras dan Soda Kue
    Campur Tepung Beras dan Soda Kue
  • Campur kentang setengah matang dengan campuran soda kue plus tepung beras (diamkan selama 5 menit).
    Kentang dicampur dengan Tepung Beras + Soda Kue
    Kentang dicampur dengan Tepung Beras + Soda Kue
  • Goreng sampai matang kentangnya
    Kentang digoreng
    Kentang digoreng
  • Kentang siap di Makan 

Cara Yang Kedua (kalau ini dari demo orang KFC):
  • Potong kentang
  • Siapkan pasta (beli di toko makanan pasta buat ngeringin air)
  • Campur sedikit pasta dengan air (kata chef KFC kebanyakan menggunakan pasta bisa menyebabkan kanker)
  • Rendam kentang dalam air yang udah dikasih pasta selama 2jam atau 3 jam
  • Tiriskan kentang selama 15-20menit
  • Campurkan dengan tepung maizena
  • Lalu goreng :)
  • Jadi deh :D

Membuat trigger di SQL Server 2005 part 2: trigger ketika delete

ide dari trigger yang akan saya utarakan disini adalah supaya ketika data di tabel pembelian terhapus, otomatis data jumlah stock barang dari barang yang terhapus di tabel pembelian tadi berkurang. kode triggernya seperti ini
create trigger kurangiStockbarang on pembelian
for delete
as
update b set b.bar_stock = b.bar_stock - d.pem_jumlah
from barang b join deleted d on b.bar_id = d.bar_id

sebenarnya hampir sama dengan kode trigger ketika penambahan barang baru, saya memberi tanda yang bercetak tebal adalah kode yang saya rubah dari kode trigger dari artikel pertama
perbedaan paling mencolok adalah untuk menangkap nilai dari tabel yang dihapus anda mengunakan tabel virtual yang bernama deleted

Membuat trigger di SQL Server 2005

saya mencoba menjelaskan dengan bahasa yg paling sedergana ya, kalau diartikan langsung ke bahasa trigger itu artinya adalah pemicu, namun jika dihubungkan ke database, trigger artinya kode SQL yang dikerjakan oleh DBMS ketika suatu kejadian terjadi.n dalam hal ini jika perintah INSERT, UPDATE, atau DELETE dijalankan di DBMS, beribet ya penjelasannya? :p
OK, saya kasih contoh sederhanan saja ya.. misalnya saya punya 2 tabel..tabel barang dan tabel pembelian, untuk lebih jelasnya bisa dilihat pada gambar dibawah ini. dalam tabel barang tersebut ada nama barang dan jumlah stock , IDEnya adalah ketika tabel pembelian ditambahkan, jumlah stock barang akan terupdate secara otomatis.misalnya ketika barang A dibeli sejumlah 3 buah maka nanti stock barang akan bertambah 3 secara otomatis. proses tersebut bisa dilakukan dgn trigger
tabeltrigger
menurut MSDN, syntac dari trigger adalah sebagai berikut
Syntax
CREATE TRIGGER trigger_name
ON { table | view }
[ WITH ENCRYPTION ]
{
{ { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
[ WITH APPEND ]
[ NOT FOR REPLICATION ]
AS
[ { IF UPDATE ( column )
[ { AND | OR } UPDATE ( column ) ]
[ ...n ]
| IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
{ comparison_operator } column_bitmask [ ...n ]
} ]
sql_statement [ ...n ]
}
}
biar lebih mengerti, kita mulai dengan contoh.. jadi kita butuh membuat 2 tabel tersebut di SQL server 2005, script sebagai berikut
create table BARANG
(
BAR_ID int not null,
BAR_NAMA varchar(255) not null,
BAR_STOCK int null
default 0,
constraint PK_BARANG primary key (BAR_ID)
)
go

create table PEMBELIAN
(
PEM_ID int not null,
BAR_ID int null ,
PEM_JUMLAH int null ,
constraint PK_PEMBELIAN primary key (PEM_ID)
)
go

create index RELATION_FK on PEMBELIAN (BAR_ID)
go

alter table PEMBELIAN
add constraint FK_PEMBELIA_RELATION_BARANG foreign key (BAR_ID)
references BARANG (BAR_ID)
go

INSERT INTO BARANG (BAR_ID,BAR_NAMA) VALUES (1,’AQUA’);
INSERT INTO BARANG (BAR_ID,BAR_NAMA) VALUES (2,’TOTAL’);
INSERT INTO BARANG (BAR_ID,BAR_NAMA) VALUES (3,’AQUADES’);

setelah anda menjalankan script tersebut, maka anda akan mempunyai 2 tabel, yaitu tabel barang dengan isi 3 buah data, dan tabel pembelian dengan data masih kosong.3 data di tabel barang tersebut secara defaut stocknya adalah 0
kemudian saatnya kita buat trigger sehingga ketika kita menambahkan data di tabel pembelian dengan jumlah pembelian barang tertentu, maka stock di tabel barang akan bertambah sesuai dengan barang yg dibeli, syntac trigger tersebut adalah sebagai berikut
create trigger tambahStockbarang on pembelian
for insert
as
update b set b.bar_stock = b.bar_stock + i.pem_jumlah
from barang b join inserted i on b.bar_id = i.bar_id

arti dari kode tersebut adalah sebagai berikut
create trigger tambahStockbarang on pembelian
membuat trigger dengan nama tambahStockBarang dimana trigger tersebut akan terpicu jika ada perubahan di tabel pembelian
for insert
as

perubahan tersebut adalah penambahan(insert) di tabel pembelian , selain penambahan bisa juga diisi dengan perubahan(update) atau penghapusan(delete)
for disini juga bisa rubah isinya jadi after atau instead of . perbedaanya adalah waktu trigger dikerjakan, biasaya yg sering digunakan adalah for
update b set b.bar_stock = b.bar_stock + i.pem_jumlah
from barang b join inserted i on b.bar_id = i.bar_id

ini adalah kode yg dikerjakan ketika kejadian trigger terpicu, kode diatas bertujuan merubah nilai bar_stock pada tabel barang dengan menambahkan nilai bar_stock yg sekarang dengan jumlah barang yg dibeli (pem_jumlah). perhatikan disini ada tabel yang bernama inserted, tabel tersebut merupakan tabel logika yg digunakan untuk menyimpan data yang memicu terjadinya trigger, dalam hal ini nilai data yg dimasukkan(insert) kedalam tabel pembelian, selain inserted, tabel logika lainnya adalah deleted, tabel logika ini digunakan untuk trigger yg terpicu dengan kejadian delete
kita coba masukkan kode berikut
INSERT INTO PEMBELIAN (PEM_ID, BAR_ID, PEM_JUMLAH) VALUES (1,1,4);
INSERT INTO PEMBELIAN (PEM_ID, BAR_ID, PEM_JUMLAH) VALUES (2,3,2);
INSERT INTO PEMBELIAN (PEM_ID, BAR_ID, PEM_JUMLAH) VALUES (3,1,1);

arti kode tersebut
pem_id haruslah beda karena merupakan primary key
beli aqua(kode bar_id=1) sebanyak 4
beli aquades (kode bar_id=3) sebanyak 2
beli aqua lagi sebanyak 1
sehingga secara keseluruhan yg dibeli aqua sebanyak 5 dan aquades sebanyak 2
karena default nilai stock barang adalah 0, maka seharusnya nilai aqua 5 dan aquades 2 adalah jumlah stock barang sekarang ini
dan kita lihat data barang… walah
hasil trigger

Tuesday, October 20, 2009

Using ExtJS Form to store data to mysql database using PHP

1. simple-form.html
<html>
 <head>
  <title>Extjs Form 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="simple-form.js"></script>
 </head> 
 <body>
 
  
  <div id="simple-form"></div>
 
 </body>
</html>

2. simple-form.js
Ext.onReady(function(){
 
 Ext.QuickTips.init();
 
 var simpleForm = new Ext.FormPanel ({
  labelWidth: 75,   // label settings here cascade unless overridden
        url:'save-form.php', // when this form submitted, data goes here
        frame:true,
        title: 'Add Pirates Crew',
        bodyStyle:'padding:5px 5px 0',
        width: 350,
        defaults: {width: 230},
        defaultType: 'textfield',
 
        items: [{
    /*
     here same as  in HTML
    */
                fieldLabel: 'Name',
                name: 'name',
                allowBlank:false
            },{
                fieldLabel: 'Position',
                name: 'position'
            },{
                fieldLabel: 'Ambition',
                name: 'ambition'
  }],    
 
        buttons: [{
            text: 'Save',   
   handler: function () {
    // when this button clicked, sumbit this form
    simpleForm.getForm().submit({
     waitMsg: 'Saving...',  // Wait Message
     success: function () {  // When saving data success
      Ext.MessageBox.alert ('Message','Data has been saved');
      // clear the form
      simpleForm.getForm().reset();
     },
     failure: function () {  // when saving data failed
      Ext.MessageBox.alert ('Message','Saving data failed');
     }
    });
   }
        },{
            text: 'Cancel',
   handler: function () {
    // when this button clicked, reset this form
    simpleForm.getForm().reset();
   }
        }]
 
 });
 
 // finally render the form
 simpleForm.render ('simple-form'); // render form to simple-form element (see simple-form.html)
 
});
 
3. save-form.php

 $conn = mysql_connect ("localhost", "root", "") or die (mysql_error ());
 mysql_select_db ("extjs") or die (mysql_error ());
 
 $q=mysql_query ("
  INSERT INTO strawhats (name, position, ambition) VALUES ('".$_POST['name']."','".$_POST['position']."','".$_POST['ambition']."')
 ") or die ('{"success":"false"}');
 
 // json output to notify the insert is success or not
 if ($q) {
  echo '{"success":"true"}';
 }
 else {
  echo '{"success":"false"}';
 }
 
?>

 

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> 

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);
?>

 

Building Simple Array Grid

First time i using Ext JS, i think how difficult to use this library. and at the first time i try to build my first grid i fail :D what i see is a blank page and i dont know what the error. but i am not give up :D, when i am surfing on the internet i found firebug. firebug is tools that integrates with Firefox. With this tool you can debug error in your javascript code. you can download firebug here
so, before we start this tutorial make sure you already install Firefox and firebug. and you already have the Ext JS library of course :). if you dont have the ExtJS library yet you can download here
lets start with the array grid (grid that the data is load from array). I use Ext-2.2 for this tutorial.
1. write the html first (array-grid.html)

<html>
<head>
<title>Array Grid Sample</title>

<link rel=”stylesheet” type=text/css” 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>
 
code here ( see part 2 ) –>
<script type=text/javascript” src=”array-grid.js”></script>
</head>
 
<body>
 

<div id=”grid-example”></div>
</body>
</html>
 
2. write the javascript (array-grid.js)
make sure your code to build grid is inside this code:

Ext.onReady (function () {
// place your code here
});
 
here the javascript code:
// make sample array data
 
var myData = [
[’3m Co’,71.72,0.02,0.03,9/1 12:00am’],
[’Alcoa Inc’,29.01,0.42,1.47,9/1 12:00am’],
[’Altria Group Inc’,83.81,0.28,0.34,9/1 12:00am’],
[’American Express Company’,52.55,0.01,0.02,9/1 12:00am’],
[’American International Group, Inc.’,64.13,0.31,0.49,9/1 12:00am’],
[’AT&T Inc.’,31.61,-0.48,-1.54,9/1 12:00am’],
[’Boeing Co.’,75.43,0.53,0.71,9/1 12:00am’],
[’Caterpillar Inc.’,67.27,0.92,1.39,9/1 12:00am’],
[’Citigroup, Inc.’,49.37,0.02,0.04,9/1 12:00am’],
[’E.I. du Pont de Nemours and Company’,40.48,0.51,1.28,9/1 12:00am’],
[’Exxon Mobil Corp’,68.1,-0.43,-0.64,9/1 12:00am’],
[’General Electric Company’,34.14,-0.08,-0.23,9/1 12:00am’],
[’General Motors Corporation’,30.27,1.09,3.74,9/1 12:00am’],
[’Hewlett-Packard Co.’,36.53,-0.03,-0.08,9/1 12:00am’],
[’Honeywell Intl Inc’,38.77,0.05,0.13,9/1 12:00am’],
[’Intel Corporation’,19.88,0.31,1.58,9/1 12:00am’],
[’International Business Machines’,81.41,0.44,0.54,9/1 12:00am’],
[’Johnson & Johnson’,64.72,0.06,0.09,9/1 12:00am’],
[’JP Morgan & Chase & Co’,45.73,0.07,0.15,9/1 12:00am’],
[’McDonald\’s Corporation’,36.76,0.86,2.40,9/1 12:00am’],
[’Merck & Co., Inc.’,40.96,0.41,1.01,9/1 12:00am’],
[’Microsoft Corporation’,25.84,0.14,0.54,9/1 12:00am’],
[’Pfizer Inc’,27.96,0.4,1.45,9/1 12:00am’],
[’The Coca-Cola Company’,45.07,0.26,0.58,9/1 12:00am’],
[’The Home Depot, Inc.’,34.64,0.35,1.02,9/1 12:00am’],
[’The Procter & Gamble Company’,61.91,0.01,0.02,9/1 12:00am’],
[’United Technologies Corporation’,63.26,0.55,0.88,9/1 12:00am’],
[’Verizon Communications’,35.57,0.39,1.11,9/1 12:00am’],
[’Wal-Mart Stores, Inc.’,45.45,0.73,1.63,9/1 12:00am’]
];
 
// create the data store
var store = new Ext.data.SimpleStore({
fields: [
{name: ‘id’, type: ‘int’},
{name:name},
{name: ‘position’},
{name: ‘ambition’}
]
});
 
// load data
 
store.loadData(sampleData);
 
// 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, dataIndex:name},
{header: ‘Position’, width: 100, dataIndex: ‘position’},
{header: ‘Ambition’, width: 250, dataIndex: ‘ambition’}
],
stripeRows: true,
height:180,
width:500,
title:’Straw Hats Crew’
});
 
// render grid to the grid-example element (see p array-grid.html)
grid.render(’grid-example’);