PDA

View Full Version : I want build a EditorGrid with PHP and MySQL



xmatt1
28 Jul 2007, 5:02 PM
Hello! please i need help :(

1. build a editor grid that get the data from MySQL and puts your texts, date, number fields. (it's ok, i did it so its Ok)

2. build a serch tool in grid editor (it's all ok, i did it tool)

3. THE BIG PROBLEM - How do i do to update grid editor to PHP and MySQL :-/ :-/ :-/

Someone, is there some great simple example that do it??

i will show u the my code

first my table in database


CREATE TABLE `fv_usuarios` (
`idUsuario` int(11) NOT NULL AUTO_INCREMENT,
`idPerfil` int(11) NOT NULL,
`nome` varchar(50) NOT NULL,
`login` varchar(12) NOT NULL,
`senha` varchar(12) NOT NULL,
`acessoAtual` datetime DEFAULT NULL,
`ultimoAcesso` datetime DEFAULT NULL,
`visitas` int(11) DEFAULT NULL,
PRIMARY KEY (`idUsuario`),
KEY `fv_usuarios_FKIndex1` (`idPerfil`),
CONSTRAINT `fv_usuarios_ibfk_1` FOREIGN KEY (`idPerfil`) REFERENCES `fv_perfis` (`idPerfil`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8


HTML FILE -> index.php
in this html file "php" i have a javascript complement for search too


<?
require_once '../includes/configure.inc.php';
require_once CLASSES.'usuarios.inc.php';
require_once 'response.php';
$usuarios = new usuarios;
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<link rel="stylesheet" type="text/css" href="../includes/ext/resources/css/ext-all.css" />
<link rel="stylesheet" type="text/css" href="../includes/ext/resources/css/xtheme-aero.css" />
<link rel="stylesheet" type="text/css" href="../includes/ext/resources/css/reset-min.css" />
<link rel="stylesheet" type="text/css" href="../includes/ext/resources/css/grid.css" />
<link rel="stylesheet" type="text/css" href="../includes/ext/examples/examples.css" />
<link rel="stylesheet" type="text/css" href="../includes/ext/examples/grid/grid-examples.css" />

<link rel="stylesheet" type="text/css" href="teste.css" />

<script type="text/javascript" src="../includes/ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../includes/ext/adapter/yui/yui-utilities.js"></script>
<script type="text/javascript" src="../includes/ext/adapter/yui/ext-yui-adapter.js"></script>
<script type="text/javascript" src="../includes/ext/ext-all.js"></script>
<script type="text/ecmascript" src="../includes/ext/source/locale/ext-lang-pt_br.js" charset="utf-8"></script>

<!-- this js files are complement for search tool -->
<script type="text/javascript" src="js_compat_pre16.js"></script>
<script type="text/javascript" src="Ext.ux.SearchField.js"></script>
<script type="text/javascript" src="ClearableTriggerField.js"></script>
<script type="text/javascript" src="ClearableCombo.js"></script>
<script type="text/javascript" src="HistoryComboBox.js"></script>
<script type="text/javascript" src="teste.js"></script>
<!-- end of complement search tool -->

</head>

<body>
<input type="button" id="show-dialog-btn" value="Please show me the form" />

<select id="idPerfil" name="idPerfil" style="display:none;">
<?
$perfis = $usuarios->dropdownPerfil();
for ( $i=0; $i<count($perfis); $i++ ) {
print '<option value="'. $perfis[$i]->idPerfil .'">'. $perfis[$i]->nome .'</option>';
}
?>
</select>

<div id="usuariosGrid"></div>
</body>
</html>



JavaScript code -> teste.js
[code]
Ext.onReady(function(){

Ext.QuickTips.init();

function formatDate(value){
return value ? value.dateFormat('d/m/Y') : '';
};

function updateDB(oGrid_event){

gridForm.submit(
{
//waitMsg: 'Saving changes, please wait...',
url:'response.php?ac=saveData&column='+oGrid_event.field+'&row='+oGrid_event.row+'&value='+oGrid_event.value, //php function that saves the data
success:function(form, action) {
alert('Congrats! Your changes were saved!!!!');
},
failure: function(form, action) {
alert('Oops the delete did not work out too well!');
}
}
);
};

var fm = Ext.form, Ed = Ext.grid.GridEditor;

var cm = new Ext.grid.ColumnModel([
{header: "C

jay@moduscreate.com
29 Jul 2007, 4:27 AM
(I hope i'm getting what you want to do).
Mateus, the logic flow is as such:

Create a button that executes a function to get the values from the data store
encode the json data using encode OR send the json as one huge chunk string
submit the data via XHR To the php server which should return {success: true}

xmatt1
30 Jul 2007, 10:20 AM
Nice my friend.. so how do i do it with json??

jay@moduscreate.com
30 Jul 2007, 5:18 PM
php5 has jsondecode functions ;)

xmatt1
31 Jul 2007, 7:55 AM
i know php5 have json_encode
but i want know how do i do to create this button and give all data modified from grid editor and save it into mySql

if u can help me so please help me!

do u have some example??

easytouch
31 Jul 2007, 12:02 PM
Here my little first trial after a few days playing with ext and PHP-mySQL on the server side.

After each 'edit' change on the grid, I send the data in
JSON format to the server URL json-upload.php

Ext does call 'afteredit' after each change to a cell. Your example is slightly different
if you want the user to edit multiple cells and you have an extra [Submit] button
somwhere on the page. But the principle of calling the servers php URL and sending
a variable that contains text in JSON format is the same. (as I have learned in the meantime)



grid.on('afteredit',function(oe) {

Ext.get('grid-paging').mask();

/**
* oe.grid - This grid
* oe.record - The record being edited
* oe.field - The field name being edited
* oe.value - The value being set
* oe.originalValue - The original value for the field, before the edit.
* oe.row - The grid row index
* oe.column - The grid column index
*/

var data = new Array;
Ext.each (grid.getDataSource().getModifiedRecords(), function(record) {
data.push(record.data);
});

var jsondata = Ext.util.JSON.encode(data);
var conn = new Ext.data.Connection();
conn.request({
method: 'POST'
, url: 'json-upload.php'
, params: { action: 'update', data: jsondata }
});

conn.on('requestcomplete', function(sender, param) {
Ext.get('grid-paging').unmask();

//alert (param.responseText);
var response = Ext.util.JSON.decode(param.responseText);
if (response.result == 'OK') {
// refresh local data ...
grid.getDataSource().commitChanges();
// ... and reload the grid
ds.load({params:{start:0, limit:myPageSize}});
// Ext.example.msg(response.result, response.message);
}
else {
Ext.MessageBox.alert(response.result, response.message);
}

}, { scope: grid });

});


On the Server sits a PHP script 'json-upload.php' that sends the changes to the mySQL database



<?php


// simulate latency
sleep(1);

$jsonResult = 'OK';
$jsonMessage = 'OK';

/**
* Get JSON 'call message' from POST variables
*/
$action = $_POST['action'];

$jsondata = $_POST['data'];
// EXAMPLE OF JSON MESSAGE.
//$jsondata = '[{"id":"3","url":"orf.com","text":"orf International"}]';

$jsonArray = json_decode($jsondata, true);

// Connect to database
$link = mysql_connect("localhost", "rootuser", "rootpassword") or die("Could not connect");

// SPECIFIC MYSQL DATABASE NAME 'test'. USE YOURS.
mysql_select_db("test") or die("Could not select database");

// Loop through results needed if the Server is slow
// and the Client has edited in the meantime data in more
// than 1 row
$loop = 0;
foreach ($jsonArray as $element) {
$loop += 1;
// extract() explodes the array.
// this are your fieldnames on the client side (grid Column definition)
// SPECIFIC EXAMPLE 'id' 'url' and 'text'. USE YOURS.
extract($element); // $id, $url, and $text are now set

/**
* Take care of the addslashes/stripslashes situation
* with your specific PHP Version, configuration, htaccess, etc...
* http://lists.evolt.org/archive/Week-of-Mon-20020812/120447.html
*/
//$url = addslashes($url);
//$text = addslashes($text);

/**
* set mySQL to UTF-8 mode for German Umlaute and
* other international characters
*/
$query = "set names 'utf8'";

$mysqlResult = mysql_query($query);
$mybic->deb("loop [$loop] mySQL utf8 queryResult: " . $mysqlResult, "mySQL utf8 Query Result");
if (!$mysqlResult) {
$jsonMessage = 'Invalid query';
$jsonResult = 'mySQL error';
break;
}

/**
* UPDATE
*/
$mybic->deb("loop [$loop] inside mySQL UPDATE because id > 0");

// SPECIFIC EXAMPLE. USE HERE YOUR MYSQL TABLE STRUCTURE
$update_query = "UPDATE log SET url = '" . $url . "', text = '" . $text . "' WHERE id = '" . $id . "'";

$mysqlResult = mysql_query($update_query);
if (!$mysqlResult) {
$jsonMessage = 'Invalid query';
$jsonResult = 'mySQL UPDATE failed';
break;
}
$jsonMessage = 'Updated id '.$id.'<br>';

} // foreach ($jsonArray as $element)

echo '{ result: "' . $jsonResult . '", message: "'. $jsonMessage .'" }';
?>


I hope this gives you some ideas for a first start.

jay@moduscreate.com
31 Jul 2007, 2:51 PM
i know php5 have json_encode
but i want know how do i do to create this button and give all data modified from grid editor and save it into mySql

if u can help me so please help me!

do u have some example??


Sorry dude, i don't have much time at the moment to provide examples. :-\

Wolfgang
1 Aug 2007, 1:59 AM
...
do u have some example??

There are some examples in the example section.

Regards

Wolfgang

bd318
3 Aug 2007, 12:36 AM
i know php5 have json_encode
but i want know how do i do to create this button and give all data modified from grid editor and save it into mySql

if u can help me so please help me!

do u have some example??


To make a button, use the following code:

if you already have a header in your grid use this:


var gridHeaderPanel = grid.getView().getHeaderPanel(true);

var tb = new Ext.Toolbar(
gridHeaderPanel,
[{
text: 'Save all changes',
handler: function() {
jsonData = "[";

for(i=0;i<ds.getCount();i++) {
record = ds.getAt(i);
if(record.data.newRecord || record.dirty) {
jsonData += Ext.util.JSON.encode(record.data) + ",";
}
}

jsonData = jsonData.substring(0,jsonData.length-1) + "]";

gridForm.submit(
{
waitMsg: 'Saving changes, please wait...',
url:'index.php',
params:{data: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!');
}
}
);
}
}]
)


otherwise add this to your header:


{
text: 'Save all changes',
handler: function() {
jsonData = "[";

for(i=0;i<ds.getCount();i++) {
record = ds.getAt(i);
if(record.data.newRecord || record.dirty) {
jsonData += Ext.util.JSON.encode(record.data) + ",";
}
}

jsonData = jsonData.substring(0,jsonData.length-1) + "]";

gridForm.submit(
{
waitMsg: 'Saving changes, please wait...',
url:'index.php',
params:{data: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!');
}
}
);
}
}


Use this line in your php-code to decode the json array (PHP 5 only):
$data = json_decode(stripslashes($_POST['data']));

It's for you to figure out how the $data array is build up and how to save ;)

Maybe you can take a look at my example how I did it:
http://extjs.com/forum/showthread.php?t=10002

Good luck!

xmatt1
22 Aug 2007, 9:45 AM
thanks! =D>