PDA

View Full Version : DataWriter Example with real MySQL db



ikkeook
21 Jun 2009, 9:20 AM
hello,

about the new datawriter for the store :

http://extjs.com/deploy/ext-3.0-rc2/examples/restful/restful.js
http://extjs.com/deploy/ext-3.0-rc2/examples/writer/writer.html

in the examples the current MVC php backend is using a session to store the information. Can someone help me to make this work with a real MySQL database?
I guess i need edit the model.php file.

thanks

23 Jun 2009, 2:40 AM
what exactly do you need help with?

ikkeook
27 Jun 2009, 11:31 PM
I just want to replace the current MVC php backend from the example by a real MySQL database. Thats all.
1) can someone do this for me? I guess other people want this also/ have already done this.
2) if not, who can tell me what i need to do. Which files i have to edit.

thanks.

mjlecomte
28 Jun 2009, 2:54 PM
Sounds like you should read up on php / MySQL. There are a few examples in the wiki and a few books for ExtJS that will help a bit with this. But depending on your application you should understand it yourself, most examples are incomplete (do not implement all of the recommended security practices, etc.).

ikkeook
6 Jul 2009, 2:30 PM
bump bump bump

lpastor
6 Aug 2009, 2:35 PM
Hello,

I need exactly the same help than ikkeook :">.

I know well php/mysql but I am newbie with ExtJS and I don't understand in which file I must put my mysql requete and what is the output format that I must generate ?

Perhaps, I need to adapte only the writer/remote/lib/session_db.php ?

Must I modify only the $_SESSION['rs'] array to update my grid ?

It is very difficult to understand the overlap of files in this example when we are discovered for the first time.

I went through all the tutorials and the forum, and I have not found a complete example with PHP and MYSQL running with Ext 3.0.

Sincerely,

Laurent

churcho
7 Aug 2009, 2:24 AM
I went through all the tutorials and the forum, and I have not found a complete example with PHP and MYSQL running with Ext 3.0.
Can be quite frustrating if you want to connect to a db and use php for data checks, displaying errors using the extjs message boxes e.t.c

Still waiting for one too

mmarsching
7 Aug 2009, 6:53 AM
Nope! You have to edit the models for each table/class.

steffenk
7 Aug 2009, 8:09 AM
I suggest to use Ext.Direct for that. Have a look here where it's done very simple and clear, fits well in MVC structure:
http://extjs.com/forum/showthread.php?t=72340

lpastor
7 Aug 2009, 8:42 AM
Thanks for your reply,

I have modified ŕ little bit writer/remote/lib/session_db.php with that :


<?php
/**
* @class SessionDB
* Fake Database. Stores records in $_SESSION
*/

//database parameters
$user='db_login'; //user
$pw='db_pwd'; //user password
$db='test'; //name of database

//make database connection
$connection = mysql_connect("localhost", $user, $pw) or
die("Could not connect: " . mysql_error());
mysql_select_db($db) or die("Could not select database");



class SessionDB {
public function __construct() {
if (!isset($_SESSION['pk'])) {
//$_SESSION['pk'] = 10; // <-- start fake pks at 10
$_SESSION['rs'] = getData(); // <-- populate $_SESSION with data.
}
}
// fake a database pk
public function pk() {
return $_SESSION['pk']++;
}
// fake a resultset
public function rs() {
return $_SESSION['rs'];
}

#Insert
public function insert($rec) {
//array_push($_SESSION['rs'], $rec);

extract($rec);

$requete="insert essai set email='$email', ";
$requete.="nom='$last', ";
$requete.="prenom='$first' ";
$res=mysql_query($requete);

$_SESSION['pk']=mysql_insert_id();

array_push ($toto, array('id' => $_SESSION['pk'], 'first' => $R['prenom'], 'last' => $R['nom'], 'email' => $R['email']));

// That is to log and debug the result in a file
$fd = fopen("RESULTAT_INSERT_LOG.TXT","w");
fputs($fd,"LOG ".date('d/m/Y - H:i:s')."\n\n");

fputs($fd,"REC : ".print_r($rec, true)."\n\n");

fputs($fd,"REQUETE : ".$requete."\n\n");

fputs($fd,"PK : ".$_SESSION['pk']."\n\n");

fputs($fd,print_r($rec, true)."\n\n");

fclose($fd);
}

# UPDATE
public function update($idx, $attributes) {
$_SESSION['rs'][$idx] = $attributes;

extract($attributes);

$requete="update essai set email='$email', ";
$requete.="nom='$last', ";
$requete.="prenom='$first' ";
$requete.="where id='$id' ";
$res=mysql_query($requete);

// That is to log and debug the result in a file
$fd = fopen("RESULTAT_UPDATE_LOG.TXT","w");
fputs($fd,"LOG ".date('d/m/Y - H:i:s')."\n\n");
fputs($fd,$requete."\n\n");
fputs($fd,print_r($attributes, true));
fclose($fd);

}

#Destroy
public function destroy($idx) {

$idx++;
$requete="delete from essai where id='$idx'";
$res=mysql_query($requete);


$fd = fopen("RESULTAT_DESTROY_LOG.TXT","w");
fputs($fd,"LOG ".date('d/m/Y - H:i:s')."\n\n");

fputs($fd,$requete."\n\n");

fclose($fd);


//$_SESSION['rs'] = getData();
return array_shift(array_splice($_SESSION['rs'], $idx, 1));

}
}

// Sample data.
function getData() {

$requete="select * from essai";
$res=mysql_query($requete);

$nbre_ligne=mysql_num_rows($res);

$toto=array();

while ($R=mysql_fetch_array($res)) {

array_push ($toto, array('id' => $R['id'], 'first' => $R['prenom'], 'last' => $R['nom'], 'email' => $R['email']));

}

// That is to log and debug the result in a file
$fd = fopen("RESULTAT_LOG.TXT","w");
fputs($fd,"LOG ".date('d/m/Y - H:i:s')."\n\n");
fputs($fd,print_r($toto, true));
fclose($fd);

return $toto;


}That works with a mysql base name (test), a table(essai) with 4 columns (id, nom, prenom, email)

To generate quickly the Mysql table in the base test :

CREATE TABLE `test`.`essai` ( `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`prenom` VARCHAR( 20 ) NOT NULL ,
`nom` VARCHAR( 20 ) NOT NULL ,
`email` VARCHAR( 50 ) NOT NULL
) ENGINE = MYISAM


I am near the solution, I have juste an ID problem to solve:-? between the grid and the php.

steffenk
7 Aug 2009, 8:47 AM
where is your session_start() ? Without it can't work!

lpastor
7 Aug 2009, 8:56 AM
session_start is in writer/remote/init.php of the example.

lpastor
8 Aug 2009, 5:32 PM
I have found what is the problem, I think it's the same like http://extjs.com/forum/showthread.php?t=72591

Finally, in the file writer/remote/lib/session_db.php, I understand that the value give by $idx to modify or destroy data isn't the id of the recordset but the number of the row in the grid.

And we can't do nothing with that in the database ! :((


# UPDATE
public function update($idx, $attributes) {

Is it a bug, or we can set that ?

This is my lastest session_db.php to work with the example :


<?php
/**
* @class SessionDB
* Fake Database. Stores records in $_SESSION
*/
//database parameters
$user='xxxx'; //user
$pw='xxxx'; //user password
$db='test'; //name of database

//make database connection
$connection = mysql_connect("localhost", $user, $pw) or
die("Could not connect: " . mysql_error());
mysql_select_db($db) or die("Could not select database");


class SessionDB {

public function __construct() {
if (!isset($_SESSION['pk'])) {
$_SESSION['pk'] = 0; // <-- start fake pks at 10
$_SESSION['rs'] = getData(); // <-- populate $_SESSION with data.
}
}
// fake a database pk
public function pk() {
return $_SESSION['pk']++;
}
// fake a resultset
public function rs() {
return $_SESSION['rs'];
}

#Insert
public function insert($rec) {
//array_push($_SESSION['rs'], $rec);

extract($rec);

$requete="insert essai set email='$email', ";
$requete.="nom='$last', ";
$requete.="prenom='$first' ";
$res=mysql_query($requete);

$titi=mysql_insert_id();
$_SESSION['pk']=$titi;


$_SESSION['rs'] = getData();


}

# UPDATE
public function update($idx, $attributes) {
$_SESSION['rs'][$idx] = $attributes;

extract($attributes);

$requete="update essai set email='$email', ";
$requete.="nom='$last', ";
$requete.="prenom='$first' ";
$requete.="where id='$id' ";
$res=mysql_query($requete);


$fd = fopen("RESULTAT_UPDATE_LOG.TXT","w");
fputs($fd,"LOG ".date('d/m/Y - H:i:s')."\n\n");

fputs($fd,$requete."\n\n");

fputs($fd,print_r($attributes, true));
fclose($fd);

}

#Destroy
public function destroy($idx) {

//$idx++;
$requete="delete from essai where id='$idx'";
$res=mysql_query($requete);


$fd = fopen("RESULTAT_DESTROY_LOG.TXT","w");
fputs($fd,"LOG ".date('d/m/Y - H:i:s')."\n\n");

fputs($fd,$requete."\n\n");

fclose($fd);

$_SESSION['rs'] = getData();
return $_SESSION['rs'];
//return array_shift(array_splice($_SESSION['rs'], $idx, 1));

}
}

// Sample data.
function getData() {

$requete="select * from essai";
$res=mysql_query($requete);

$nbre_ligne=mysql_num_rows($res);

$toto=array();

while ($R=mysql_fetch_array($res)) {

array_push ($toto, array('id' => $R['id'], 'first' => $R['prenom'], 'last' => $R['nom'], 'email' => $R['email']));

}


return $toto;


/*
return array(
array('id' => 1, 'first' => "Fred", 'last' => 'Flintstone', 'email' => '[email protected]'),
array('id' => 2, 'first' => "Wilma", 'last' => 'Flintstone', 'email' => '[email protected]'),
array('id' => 3, 'first' => "Pebbles", 'last' => 'Flintstone', 'email' => '[email protected]'),
array('id' => 4, 'first' => "Barney", 'last' => 'Rubble', 'email' => '[email protected]'),
array('id' => 5, 'first' => "Betty", 'last' => 'Rubble', 'email' => '[email protected]'),
array('id' => 6, 'first' => "BamBam", 'last' => 'Rubble', 'email' => '[email protected]')
);
*/

}


Laurent

lpastor
9 Aug 2009, 7:14 AM
I have solved my problem with this session_db.php :


<?php
/**
* @class SessionDB
* Fake Database. Stores records in $_SESSION
*/
//database parameters
$user='xxx'; //user
$pw='xxx'; //user password
$db='test'; //name of database

//make database connection
$connection = mysql_connect("localhost", $user, $pw) or
die("Could not connect: " . mysql_error());
mysql_select_db($db) or die("Could not select database");


class SessionDB {

public function __construct() {
if (!isset($_SESSION['pk'])) {
$_SESSION['pk'] = 0;
$_SESSION['rs'] = getData(); // <-- populate $_SESSION with data.
}
}

public function pk() {
return $_SESSION['pk']++;
}

public function rs() {
return $_SESSION['rs'];
}

#Insert
public function insert($rec) {

extract($rec);

$requete="insert essai set email='$email', ";
$requete.="nom='$last', ";
$requete.="prenom='$first' ";
$res=mysql_query($requete);

$new_id=mysql_insert_id();

$rec=array('id' => $new_id, 'first' => $first, 'last' => $last, 'email' => $email);
array_push($_SESSION['rs'], $rec);
$_SESSION['pk']=$new_id+1;


}

# UPDATE
public function update($idx, $attributes) {

extract($_SESSION['rs'][$idx]); // Pour retrouver le id ŕ supprimer - to find id to delete

extract($attributes,EXTR_PREFIX_ALL,"new"); // Pour retrouver les nouvelles valeurs - to find new variable

$requete="update essai set email='$new_email', ";
$requete.="nom='$new_last', ";
$requete.="prenom='$new_first' ";
$requete.="where id='$id' ";
$res=mysql_query($requete);


$_SESSION['rs'][$idx] = $attributes;

}

#Destroy
public function destroy($idx) {

extract($_SESSION['rs'][$idx]); // Pour retrouver le id ŕ supprimer - to find id to delete

$requete="delete from essai where id='$id'";
$res=mysql_query($requete);

return array_shift(array_splice($_SESSION['rs'], $idx, 1));

}
}

// Sample data.
function getData() {

$requete="select * from essai";
$res=mysql_query($requete);

$nbre_ligne=mysql_num_rows($res);

$result=array();

while ($R=mysql_fetch_array($res)) {

array_push ($result, array('id' => $R['id'], 'first' => $R['prenom'], 'last' => $R['nom'], 'email' => $R['email']));

}


return $result;


}In the writer.js you would insert : store.load(); in the var store = new Ext.data.Store({ section to force the refresh after an add.


listeners: {
write : function(store, action, result, response, rs) {
App.setAlert(response.success, response.message);
store.load(); // Ajouté pour forcer le rafraichissement - Add to force the refresh of the data - LP
}
}

This solution work too for the restful example.

Have fun,

Laurent

churcho
10 Aug 2009, 12:39 AM
Can anyone help with this: Sorry for derailing
http://extjs.com/forum/showthread.php?t=76674

mmarsching
10 Aug 2009, 5:25 AM
If your goal is to use just one DB and one table this version may be perfect for you... the "more flexible" way is to edit the essai.php in /remote/app/models (as shown in the examples) and to use your RESTful functions in there. That way you can use more than one model/table within your application.

churcho
10 Aug 2009, 10:29 PM
The thing is I want to use this in a different setting. Here is my form code, I don't think the msg bit works, I am a newbie in this zone.


Ext.onReady(function(){

Ext.QuickTips.init();

// turn on validation errors beside the field globally
Ext.form.Field.prototype.msgTarget = 'side';

var bd = Ext.getBody();

/*
* ================ Form 5 =======================
*/
bd.createChild({tag: 'h2', html: 'Add Projects'});

var projectForm = new Ext.FormPanel({
url:"save-form.php",
id: "projectForm",
labelAlign: 'top',
title: 'Add Project Details',
bodyStyle:'padding:5px',
width: 600,


items: [{
layout:'column',
border:false,
items:[{
columnWidth:.5,
layout: 'form',
border:false,
items: [{
xtype:'textfield',
fieldLabel: 'Project Title:',
name: 'ptitle',
anchor:'95%'
}, {
xtype:'textfield',
fieldLabel: 'Priority Area:',
name: 'priorityarea',
anchor:'95%'
}]
},{
columnWidth:.5,
layout: 'form',
border:false,
items: [{
xtype:'textfield',
fieldLabel: 'Division Unit:',
name: 'unit',
anchor:'95%'
},{
xtype:'textfield',
fieldLabel: 'Time Frame/Date:',
name: 'email',
vtype:'email',
anchor:'95%'
}] },{
columnWidth:.5,
layout: 'form',
border:false,
items: [{
xtype:'textfield',
fieldLabel: 'Contact Name:',
name: 'cname',
anchor:'95%'
},{
xtype:'textfield',
fieldLabel: 'Contact Email:',
name: 'email',
vtype:'email',
anchor:'95%'
}]
},{
columnWidth:.5,
layout: 'form',
border:false,
items: [{
xtype:'textfield',
fieldLabel: 'Contact Extention:',
name: 'telext',
anchor:'95%'
},{
xtype:'textfield',
fieldLabel: 'Contact Mobile:',
name: 'telmobile',
anchor:'95%'
}]
//end of section
}]
},{
xtype:'tabpanel',
plain:true,
activeTab: 0,
height:335,
defaults:{bodyStyle:'padding:10px'},
items:[{


title:'Project Objectives',
layout:'fit',

items: {
xtype:'htmleditor',
id:'bio2',
fieldLabel:'Biography'
}
},
//end of first tab
{
title:'More Details',
layout:'form',
defaults: {width: 530},
defaultType: 'textarea',

items: [{
fieldLabel: 'Potential Synergies/ Partnerships:',
name: 'partnerships',
value: ''
},{
fieldLabel: 'Communication Tools Desired:',
name: 'comtools',
value: ''
},{
fieldLabel: 'Proposed Budget (For Communication Projects Only)',
name: 'comtools',
value: ''
}
]
},



]
}],

buttons: [{
text: "Save",
handler: function() {
if (Ext.getCmp("projectForm").getForm().isValid()) {
submitForm();
}
}
},{
text: "Cancel"
}]
});
projectForm.render(document.body);

var formOnSuccessorFail = function(form, action) {
var result = action.result;
if (result.success) {
Ext.getCmp("projectForm").el.unmask();
Ext.MessageBox.alert("Success!", "Form submitted");
} else {
Ext.getCmp("projectForm").el.unmask();
Ext.MessageBox.alert("Error", "Form not submitted");
}
}

var submitForm = function() {
var form = Ext.getCmp("projectForm");
form.el.mask("Subbmitting Project Details...", "x-mask-loading");
form.getForm().submit({
url: "projAdd.php",
success: formOnSuccessorPass,
failure: formOnSuccessorFail
});
}

});

How would one connect to a database and show messages based on output from the php file? Is the concept the same on all these?

christocracy
15 Aug 2009, 9:05 AM
That imaginary php MvC (small "v" since it has no View) backend behind the DataWriter/RESTful examples was whipped up in a couple of days. I highly recommend against using that thing for any kind of production use.

For PHP, I'd use Code-Igniter, Symphony or search for PHP/Rails ports.

evang
18 May 2010, 9:25 PM
I have solved my problem with this session_db.php :


<?php
/**
* @class SessionDB
* Fake Database. Stores records in $_SESSION
*/
//database parameters
$user='xxx'; //user
$pw='xxx'; //user password
$db='test'; //name of database

//make database connection
$connection = mysql_connect("localhost", $user, $pw) or
die("Could not connect: " . mysql_error());
mysql_select_db($db) or die("Could not select database");


class SessionDB {

public function __construct() {
if (!isset($_SESSION['pk'])) {
$_SESSION['pk'] = 0;
$_SESSION['rs'] = getData(); // <-- populate $_SESSION with data.
}
}

public function pk() {
return $_SESSION['pk']++;
}

public function rs() {
return $_SESSION['rs'];
}

#Insert
public function insert($rec) {

extract($rec);

$requete="insert essai set email='$email', ";
$requete.="nom='$last', ";
$requete.="prenom='$first' ";
$res=mysql_query($requete);

$new_id=mysql_insert_id();

$rec=array('id' => $new_id, 'first' => $first, 'last' => $last, 'email' => $email);
array_push($_SESSION['rs'], $rec);
$_SESSION['pk']=$new_id+1;


}

# UPDATE
public function update($idx, $attributes) {

extract($_SESSION['rs'][$idx]); // Pour retrouver le id ŕ supprimer - to find id to delete

extract($attributes,EXTR_PREFIX_ALL,"new"); // Pour retrouver les nouvelles valeurs - to find new variable

$requete="update essai set email='$new_email', ";
$requete.="nom='$new_last', ";
$requete.="prenom='$new_first' ";
$requete.="where id='$id' ";
$res=mysql_query($requete);


$_SESSION['rs'][$idx] = $attributes;

}

#Destroy
public function destroy($idx) {

extract($_SESSION['rs'][$idx]); // Pour retrouver le id ŕ supprimer - to find id to delete

$requete="delete from essai where id='$id'";
$res=mysql_query($requete);

return array_shift(array_splice($_SESSION['rs'], $idx, 1));

}
}

// Sample data.
function getData() {

$requete="select * from essai";
$res=mysql_query($requete);

$nbre_ligne=mysql_num_rows($res);

$result=array();

while ($R=mysql_fetch_array($res)) {

array_push ($result, array('id' => $R['id'], 'first' => $R['prenom'], 'last' => $R['nom'], 'email' => $R['email']));

}


return $result;


}In the writer.js you would insert : store.load(); in the var store = new Ext.data.Store({ section to force the refresh after an add.


listeners: {
write : function(store, action, result, response, rs) {
App.setAlert(response.success, response.message);
store.load(); // Ajouté pour forcer le rafraichissement - Add to force the refresh of the data - LP
}
}

This solution work too for the restful example.

Have fun,

Laurent

great! but how to add paging function? thx

PaulyWolly
9 Jan 2012, 9:27 AM
Has anyone been able to successfully write back-end code for the new version of EXTJS 4 and for the writer.js example? I am having a hard time trying to figure out how to convert the code that writes to a SESSION into code that writes to a actual MySQL database using PHP as the server side.