1. #1
    Ext User
    Join Date
    Jul 2007
    Posts
    29
    Vote Rating
    0
    bd318 is on a distinguished road

      0  

    Default Example of editor-grid using php and mysql to save data

    Example of editor-grid using php and mysql to save data


    Updated post:

    I made an update for this example. To make sure all new readers see this instead of the post before, I edit it here.
    The new WORKING example is as followed:

    The js file:
    PHP Code:
     var GridUI = function() {
         
    //enable Quicktips
        
    Ext.QuickTips.init();
        
         
    //set vars
        
    var ds//datastore for grid
        
    var cm//columnModel
        
    var grid//component
        
    var fm Ext.formEd Ext.grid.GridEditor// shorthand alias    
        
        //create the datastores    
        
    function setupDataSource() {
            
    //create the Data Store for the grid    
            
    ds = new Ext.data.Store({
                
    //set the http-proxy (link to the php document)
                
    proxy: new Ext.data.ScriptTagProxy({
                
    url'sample.php?ac=showData' //a function in your php-script must be activated when ac = showdata
            
    }),
            
            
    //set up the JsonReader
            
    reader: new Ext.data.JsonReader({
                
    root'results',
                
    totalProperty'total',
                
    id'id'
            
    },[ 
                {
    name'name'type'string'mapping'name'//columnmapping
                
    ])
            });
            
            
    //load datastores
            
    ds.load();
        }     
        
        
    //create the columnmodel
        
    function getColumnModel() {
            
    cm = new Ext.grid.ColumnModel([{
                  
    header"Names",
                  
    dataIndex'name',
                  
    width150,
                 
    editor: new Ed(new fm.TextField({
                    
    allowBlanktrue,
                    
    maxLength50
                
    }))
             }]);
            
            
    //set the default for sorting the columns
            
    cm.defaultSortable false;
            
            return 
    cm;
        }    
        
        
    //create the grid
        
    function buildGrid() {    
            
    //create the form
            
    var gridForm = new Ext.form.Form({});
            
            
    //create the grid
            
    var grid = new Ext.grid.EditorGrid('editor-grid', {
                
    dsds,
                
    cmgetColumnModel(),
                
    enableColLock:false,
                
    selModel: new Ext.grid.RowSelectionModel({singleSelect:true})
            });
            
            
    //set the layout for the grid
            
    var layout Ext.BorderLayout.create({
                
    center: {
                    
    margins:{left:3,top:3,right:3,bottom:3},
                    
    panels: [new Ext.GridPanel(grid)]
                }
            }, 
    'grid-panel');
            
            
    //render the grid
            
    grid.render();
            
            
    //set the header
            
    var gridHead grid.getView().getHeaderPanel(true);
        
            var 
    tb = new Ext.Toolbar(gridHead, [{}]);
            
            
    //activate function updateDB when a cell is edited
            
    grid.on('afteredit'updateDB);
            
            function 
    updateDB(oGrid_event){
                
    gridForm.submit(
                    {
                        
    //waitMsg: 'Saving changes, please wait...',
                        
    url:'sample.php?ac=saveData&field='+oGrid_event.field+'&row='+oGrid_event.row+'&value='+oGrid_event.value//php function that saves the data
                        
    success:function(formaction) {
                            
    alert('Congrats!  Your changes were saved!!!!');
                        },
                        
    failure: function(formaction) {
                            
    alert('Oops the delete did not work out too well!');
                        }
                    }
                );
            }
            
            
    //render form
            
    gridForm.render('editGrid');
        }

         return {
             
    //the init
            
    init : function() {
                
    setupDataSource();
                
    buildGrid();
            },
            
            
    getDataSource: function() {
                return 
    ds;
            }
        }
    }();

    Ext.onReady(GridUI.initGridUItrue); 
    The php-file:
    PHP Code:
    <?php

    //make database connection
    mysql_connect("localhost""YOUR USERNAME""YOUR PASSWORD") or
       die(
    "Could not connect: " mysql_error());
    mysql_select_db("YOUR DATABASE");

    if(isset(
    $_GET['ac']) && $_GET['ac']=='showData')
        
    showData();
    elseif(isset(
    $_GET['ac']) && $_GET['ac']=='saveData')
        
    saveData($_GET['field'], $_GET['row'], $_GET['value']);

    function 
    showData() 
    {
        
    //query with data
        
    $result mysql_query("SELECT id, name FROM names");
        
    $rows mysql_num_rows($result);
        
        while(
    $rec mysql_fetch_array($result))
            
    $arr[] = $rec;
                
        echo 
    $_GET['callback'].'({"total":"'.$rows.'","results":'.json_encode($arr).'})';
    }

    function 
    saveData($field$row$value)
    {
        
    /*
         * field: the dataIndex which is being updated
         * $row: the row that is being updated
         * $value: the new value
         */ 
        
        //look which record is being updated
        
    $result mysql_query("SELECT id FROM names");
        
        while(
    $rec mysql_fetch_array($result))
            
    $id[] = $rec['id']; 
        
        
    //NOTE: this isn't the best way to save your data! 
        //What I do is look in the database and put all the ID's in an array. 
        //Then I know that $row is the right array index.
        //But when you change the order of the records for example, this isn't enough to know the row
        //However, this example works :)
            
        //save data to database
        
    if($field=='name'//the field name is being updated
            
    $result mysql_query("UPDATE `names` SET `name` = '$value' WHERE `id`='$id[$row]';");
    }
    ?>
    The html-file:
    PHP Code:
    <html>
    <
    head>
        <
    title>Sample of a grid</title>
        <
    script language="JavaScript" type="text/javascript" src="adapter/ext/ext-base.js"></script>
        <script language="JavaScript" type="text/javascript" src="ext-all.js"></script>
        <script language="JavaScript" type="text/javascript" src="sample.js"></script>
        <link rel="stylesheet" type="text/css" href="resources/css/ext-all.css" media="screen" />
    </head>
    <body>

    <div id="grid-panel" style="width:1024px;height:668px;">
    <div id="editor-grid"></div>

    <div id="editGrid">
    </div>

    </div>

    </body>
    </html> 
    The database:
    PHP Code:
    -- 
    -- 
    Table structure for table `names`
    -- 

    CREATE TABLE `names` (
      `
    idint(8unsigned NOT NULL auto_increment,
      `
    namevarchar(50NOT NULL,
      
    PRIMARY KEY  (`id`)
    ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=;

    -- 
    -- 
    Dumping data for table `names`
    -- 

    INSERT INTO `names` (`id`, `name`) VALUES 
    (1'Testname'),
    (
    2'Testname2'),
    (
    3'Testname3'),
    (
    4'Testname4'); 
    You acces the grid by going to the sample.html page!

    NOTE: Don't forget to set your database username and password in the php-file and include ext-base.js and ext-all.js!!



    First post:

    In my search on this forum to read a DataStore, display the data in a grid, edit the cells in a grid and then update the database using php and mysql I couldn't find a full working sample. So, now I found out how to do it, I want to share it with you all.

    I made the example as easy as possible. Because I'm a new EXT user, there are probably better known ways to update your database, but the example I made must work after a little editting (you have to make your queries for selecting data yourself!) and will hopefully help all the others I saw looking for help on this.

    With help of other posts from users (thanks all) I came to the following code.

    Create your grid (to make it easy, I made one column): sample.js
    PHP Code:
     var GridUI = function() {
         
    //enable Quicktips
        
    Ext.QuickTips.init();
        
         
    //set vars
        
    var ds//datastore for grid
        
    var cm//columnModel
        
    var grid//component
        
    var fm Ext.formEd Ext.grid.GridEditor// shorthand alias    
        
        //create the datastores    
        
    function setupDataSource() {
            
    //create the Data Store for the grid    
            
    ds = new Ext.data.Store({
                
    //set the http-proxy (link to the php document)
                
    proxy: new Ext.data.ScriptTagProxy({
                
    url'index.php?ac=showdata' //a function in your php-script must be activated when ac = showdata
            
    }),
            
            
    //set up the JsonReader
            
    reader: new Ext.data.JsonReader({
                
    root'results',
                
    totalProperty'total',
                
    id'id'
            
    }, 
                {
    nametesttype'string'mapping'test'//columnmapping
                
    )
            });
            
            
    //load datastores
            
    ds.load();
        }     
        
        
    //create the columnmodel
        
    function getColumnModel() {
            
    cm = new Ext.grid.ColumnModel([{
                  
    header"Testcolumn",
                  
    dataIndex'test',
                  
    //width: 150,
                 
    editorfalse
             
    }]);
            
            
    //set the default for sorting the columns
            
    cm.defaultSortable false;
            
            return 
    cm;
        }    
        
        
    //create the grid
        
    function buildGrid() {    
            
    //create the form
            
    var gridForm = new Ext.form.Form({});
            
            
    //create the grid
            
    var grid = new Ext.grid.EditorGrid('editor-grid', {
                
    dsds,
                
    cmgetColumnModel(),
                
    enableColLock:false,
                
    selModel: new Ext.grid.RowSelectionModel({singleSelect:true})
            });
            
            
    //set the layout for the grid
            
    var layout Ext.BorderLayout.create({
                
    center: {
                    
    margins:{left:3,top:3,right:3,bottom:3},
                    
    panels: [new Ext.GridPanel(grid)]
                }
            }, 
    'grid-panel');
            
            
    //render the grid
            
    grid.render();
            
            
    //set the header
            
    var gridHead grid.getView().getHeaderPanel(true);
        
            var 
    tb = new Ext.Toolbar(gridHead, [{}]);
            
            
    //activate function updateDB when a cell is edited
            
    grid.on('afteredit'updateDB);
            
            function 
    updateDB(oGrid_event){
                
    jsonData "[";
                            
                            for(
    i=0;i<ds.getCount();i++) {
                                
    record ds.getAt(i);
                                
    jsonData += Ext.util.JSON.encode(record.data) + ",";
                            }
                            
                            
    jsonData jsonData.substring(0,jsonData.length-1) + "]";
                            
                            
    gridForm.submit(
                                {
                                    
    //waitMsg: 'Saving changes, please wait...',
                                    
    url:'index.php?ac=saveData'//php function that saves the data
                                    
    params:{data:jsonData},
                                    
    success:function(formaction) {
                                        
    alert('Congrats!  Your changes were saved!!!!');
                                    },
                                    
    failure: function(formaction) {
                                        
    alert('Oops the delete did not work out too well!');
                                    }
                                }
                            );
            }
            
            
    //render form
            
    gridForm.render('editGrid');
        }

         return {
             
    //the init
            
    init : function() {
                
    setupDataSource();
                
    buildGrid();
            },
            
            
    getDataSource: function() {
                return 
    ds;
            }
        }
    }();

    Ext.onReady(GridUI.initGridUItrue); 
    The HTML-code: index.tpl
    PHP Code:
    <html>
    <
    head>
    <
    script src="ext-all.js" type="text/javascript"></script>
    <script src="adapter/ext/ext-base.js" type="text/javascript"></script>
    <script src="sample.js" type="text/javascript"></script>

    <link href="resources/css/ext-all.css" media="screen" rel="Stylesheet" type="text/css" />
    </head>
    <body>
    <div id="grid-panel" style="width:1024px;height:668px;">
    <div id="editor-grid"></div>

    <div id="editGrid">
    </div>
    </div>
    </body>
    </html> 
    The php code (index.php):

    PHP Code:
        function showData()
        {
            
    //make your query here that selects all your data for the grid
            //you have to modify the $res and fetch yourself to make the query succesfull
            
    $res $this->dbi->query('your query here');
                    
            while(
    $obj =& $this->dbi->fetch())                
            {
                
    $arr[] = $obj
            }
            
    //encode your data for the jsonreader
            
    echo $_GET['callback'].'({"total":"'.$rows.'","results":'.json_encode($arr).'})';
        }

        function 
    saveData()
        {
            
    $data json_decode(stripslashes($_POST['data']));
            
            
    //make here a query that updates the database
        

    Remember you still have to do some work yourself: make the database queries and modify the ColumnModel and DataStore so it matches your data.

    $data in saveData() is an 2D array, which you have to read by a foreach loop and put it in the database. Use echo var_dump($data); to see how the array is build!
    Note that in this example the whole grid is submitted once you edit a sell, so if you have a 100+ record grid it becomes slower and slower.

    When I find out how, I post an example in this topic how to update only one cell in the database after editing.

    Good luck!
    Last edited by bd318; 2 Aug 2007 at 11:43 PM. Reason: updated example

  2. #2
    Ext User
    Join Date
    Jul 2007
    Posts
    10
    Vote Rating
    0
    akbeyfb is on a distinguished road

      0  

    Default


    hi it looks helpfull for the new ext users like me is it possible to give us to your work with the source files.i couldnt run on my local server

  3. #3
    Ext User
    Join Date
    Jul 2007
    Posts
    29
    Vote Rating
    0
    bd318 is on a distinguished road

      0  

    Default


    I found out how I can update only one cell. In the sample.js file, change the function updateDB to the following:

    PHP Code:
      function updateDB(oGrid_event){ 
                            
    gridForm.submit
                                { 
                                    
    //waitMsg: 'Saving changes, please wait...', 
                                    
    url:'index.php?ac=saveData&column='+oGrid_event.field+'&row='+oGrid_event.row+'&value='+oGrid_event.value//php function that saves the data 
                                    
    success:function(formaction) { 
                                        
    alert('Congrats!  Your changes were saved!!!!'); 
                                    }, 
                                    
    failure: function(formaction) { 
                                        
    alert('Oops the delete did not work out too well!'); 
                                    } 
                                } 
                            ); 
            } 
    Ofcourse, you can give the url whatever value you want, but (atleast for me), I know when I have the columnid and rowid what value is updated.
    So in the PHP you have to change the query to what is updated (it's depending of the column and row). You can work something out like:

    PHP Code:
    If($column==$row==1
    {
        
    //update query (nowing for example that column1 contains names and row 1 is the second user)


  4. #4
    Ext User
    Join Date
    Jul 2007
    Posts
    10
    Vote Rating
    0
    akbeyfb is on a distinguished road

      0  

    Default


    i got this error message :Ext.QuickTips is null or is not an object..

  5. #5
    Ext User
    Join Date
    Jul 2007
    Posts
    29
    Vote Rating
    0
    bd318 is on a distinguished road

      0  

    Default


    Make sure you have the includes of the ext-all.js and ext-base.js correct (modify index.tpl if needed). Hopefully that's the problem.

    I'll try to get an working example later with source files.

  6. #6
    Ext User
    Join Date
    Jul 2007
    Posts
    1
    Vote Rating
    0
    laozhuang is on a distinguished road

      0  

    Default


    I post the submit action to MyServlet,

    gridForm.submit(
    {
    //waitMsg: 'Saving changes, please wait...',
    url:'http://localhost:8080/MyServlet',
    params:{JSON_OBJECT:jsonData},
    success:function(form, action) {
    alert('Congrats! Your changes were saved!!!!');
    },
    failure: function(form, action) {
    alert('Oops the delete did not work out too well!');
    }
    }
    );

    MyServlet work well but the action response is 'failure'.
    How can I track the failure message.
    Thank you very much

  7. #7
    Ext User cluettr's Avatar
    Join Date
    Apr 2007
    Location
    Boston, MA
    Posts
    336
    Vote Rating
    0
    cluettr is on a distinguished road

      0  

    Default


    Awesome, with a post like this you'll be sure to save a newbie some time and help get them up to speed much faster!

  8. #8
    Ext User
    Join Date
    Jul 2007
    Posts
    9
    Vote Rating
    0
    perthkit is on a distinguished road

      0  

    Default


    Thanks for your code.

    However, I couldn't make it work. like
    sample.js, line 26:
    {name: test, type: 'string', mapping: 'test'} -or- {name: 'test', type: 'string', mapping: 'test'}

    It will be great if you can post the sql file with the table structure and simple data which we can play around. If it is too much, it will be great if you can post the raw json data for index.php?ac=showdata.

    Thanks again.

  9. #9
    Ext User
    Join Date
    Jul 2007
    Posts
    5
    Vote Rating
    0
    ccquiles is on a distinguished road

      0  

    Default


    YES! thanks for your code... however I could not get it to work either... I do not get any errors, but nothing happens and I don't see the 'saving data' or either of the alerts in the updateDB function... any ideas?

  10. #10
    Ext User
    Join Date
    Jul 2007
    Posts
    29
    Vote Rating
    0
    bd318 is on a distinguished road

      0  

    Default


    I updated the initial post with a tested and working example!
    All that had errors, try again please with the new code

film izle

hd film izle

film sitesi

takipci kazanma sitesi

takipci kazanma sitesi

güzel olan herşey

takipci alma sitesi

komik eğlenceli videolar