PDA

View Full Version : delete row from database



robin30
19 Sep 2007, 7:16 PM
hi all,

One little question, if that's ok.

in the header of my grid i have a button (delete row) when i click on this the row that i selected will be deleted from the grid but not from my database.

in my js file i use:

var tb = new Ext.Toolbar(gridHead, [{
text: 'Delete Row',
handler: function() {
selectedRow = grid.getSelectionModel().getSelected();
if(selectedRow) {
gridForm.submit(
{
waitMsg: 'Deleting row, please wait...',
url:'delete.php',
params:{rowid:selectedRow.data.id},
success:function(form, action) {
ds.remove(selectedRow);
},
failure: function(form, action) {
alert('Oops the delete did not work out too well!');
}
}
);
}
}
}]);

my php file:


mysql_connect("localhost", "blablabla", "blablablabla") or
die("Could not connect: " . mysql_error());
mysql_select_db("test");

$result = mysql_query("SELECT id FROM bills");

while($rec = mysql_fetch_array($result))
$id[] = $rec['id'];
$result = mysql_query("delete from `bills` WHERE `id`='$id[$row]';");

in my database i have id, name, description, due, amount, paid, paid_when
in my grid i have a column that shows the id from my database.

When i check with firebug it deleted the right id from the grid but it won't delete that id from my database.

i got the code for deletion of the row in the grid from here
http://extjs.com/forum/showthread.php?t=8488

the where part of my php file i got from the edit-grid example.

Hopefully somebody can help me, would really appreciate it, thanks

regards,

Robin30

robin30
19 Sep 2007, 8:19 PM
hi all,

i changed this:

url:'delete.php',

into this:

url:'delete.php?id='+selectedRow.data.id,

in my php file i did put

$lol = $_POST['id'];

when i check in firebug it says http://localhost/test/delete?id=54
and 54 is the id number of the record i wanna delete in my database.

but if i put this in my php file

$result = "delete from `bills` WHERE `id`='$lol;'";
$sql=mysql_query($result);

i do get this error:
missing ) in parenthetical
http://localhost/test/ext-all.js
Line 24

what am i doing wrong, am i getting a bit closer?

thanks,

Robin

thejdog
19 Sep 2007, 10:34 PM
$result = "delete from `bills` WHERE `id`='$lol;'";
$sql=mysql_query($result);

i do get this error:
missing ) in parenthetical
http://localhost/test/ext-all.js
Line 24


Well from the first thing I notice that should be taken care of is the:


$result = "delete from `bills` where `id` = '$lol;'";

It should be:


$result = "delete from `bills` where `id` = '$lol'";

You have a extra ; in your query - that shouldn't be there. Which could be causing a issue to your javascript.

thejdog
19 Sep 2007, 10:40 PM
success:function(form, action) {
ds.remove(selectedRow);
},



Also I would put some type of error checking into there. What if your database doesn't find that row? If the AJAX call get's a 200 header from the PHP file, it will automatically assume that it's a "successful" call, it will know no difference.

Here's a brief example of my own type of code for a success:



success: function (loginForm, a) {
if( a.result.success == 'true' ) {
loginDlg.hide();
setupLayout();
} else {
Ext.Msg.alert('Login Failed', 'Username and/or password were incorrect! Please try again!');
}
}


Basically if my php file I'm calling comes back and just displays true, it was a correct login, otherwise you can just assume that it failed so display the other.

Success just means that the header response was a 200 and not a 401, 404, 503, etc.

robin30
20 Sep 2007, 3:08 AM
your answer worked thejdog, thanks.

the error was caused by this


while($rec = mysql_fetch_array($result))
$id[] = $rec['id'];

i removed it and changed $lol; into $lol and it works.

Thanks

regards,
robin

robin30
20 Sep 2007, 3:16 AM
this doesn't work thejdog,


success: function (loginForm, a) {
if( a.result.success == 'true' ) {
loginDlg.hide();
setupLayout();
} else {
Ext.Msg.alert('Login Failed', 'Username and/or password were incorrect! Please try again!');
}
}

firebug says that result is undefined

thanks

Animal
20 Sep 2007, 3:23 AM
If that's a success handler to a form submission, then it should be passed the Action as the second parameter, and that should have a result property.

What does a look like when you expand it in Firebug?

robin30
20 Sep 2007, 3:56 AM
hi animal,

i'm a completely newbee coming to extjs.

everywhere in the file it mentioned

success: function (form, action)

so i thought i have to use that too here. so i had


success: function (form, action) {
if( action.result.success == 'true' ) {
ds.remove(selectedRow);
} else {
Ext.Msg.alert('Something went wrong! Please try again!');
}
}

when i use this firebug says result = undefined.

fay
20 Sep 2007, 4:12 AM
Robin,

Is your 'delete.php' actually writing back {success: true} a la http://extjs.com/forum/showthread.php?p=63495#post63495?

robin30
20 Sep 2007, 4:22 AM
i have a button in the header

this is what i have now and it works.

var gridHead = grid.getView().getHeaderPanel(true);
var tb = new Ext.Toolbar(gridHead, [{
text: 'Delete Row',
handler: function() {
selectedRow = grid.getSelectionModel().getSelected();
if(selectedRow) {
gridForm.submit(
{
waitMsg: 'Deleting row, please wait...',
url:'delete.php?id='+selectedRow.data.id,
params:{rowid:selectedRow.data.id},
success: function (form, action) {
ds.remove(selectedRow);
Ext.Msg.show({
title:'Confirmation',
msg: 'Data Successfully Deleted.',
buttons: Ext.Msg.OK
})
},
failure: function(form, action) {Ext.Msg.show({
title:'Confirmation',
msg: 'Something Went Wrong, Please Try Again.',
buttons: Ext.Msg.OK,
})
}
}
);
}
}
}]);

all that i have to figure out that when i select a row and press the delete row button that it will ask me if i'm sure if i wanna delete it. but that's what i'm working on it now.

Animal
20 Sep 2007, 4:25 AM
And what if the deletion does not take place due to a server error?

You pop up a message saying 'Data Successfully Deleted.'!

fay
20 Sep 2007, 4:28 AM
Ext.Msg.show() has a fn handler you can use - http://extjs.com/deploy/ext/docs/output/Ext.MessageBox.html#show

See also MessageBox example - http://extjs.com/deploy/ext/examples/dialog/msg-box.html

Just watch this:


title:'Confirmation',
msg: 'Something Went Wrong, Please Try Again.',
buttons: Ext.Msg.OK,
})

The additional comma will give you problems in IE - http://extjs.com/forum/showthread.php?t=503

robin30
20 Sep 2007, 4:46 AM
but that's what i thought the


failure: function(form, action) {Ext.Msg.show({
title:'Confirmation',
msg: 'Something Went Wrong, Please Try Again.',
buttons: Ext.Msg.OK,
})

was for animal.

if i see it wrong please tell me. only way to learn.

i'm checking into it right now fay thanks.

my official question for this thread has been answered and it works. should i put [solved] in the title of the first post?

fay
20 Sep 2007, 5:19 AM
AFAIK the failure() handler is for when the server cannot be accessed for some reason, e.g., it's offline. (Or if the server throws an unhandled exception...?)

The success() handler just means that the server could process your request - it does not mean that the logic of your request was *successful*. What you code on the server page should determine that, e.g., the specified record was/was not deleted, and either return {success: true} or {success: false}. You then can test action.result.success in your success() handler and display an appropriate message.

robin30
20 Sep 2007, 5:56 AM
now i get it, thanks fay, will look into it.

like i said i'm a newbee, sorry,

thanks for taking time helping me,

Regards,

Robin

robin30
20 Sep 2007, 6:09 AM
i'm really lost now.

i changed your code


success: function (loginForm, a) {
if( a.result.success == 'true' ) {
loginDlg.hide();
setupLayout();
} else {
Ext.Msg.alert('Login Failed', 'Username and/or password were incorrect! Please try again!');
}
}

into this


success: function (form, a) {
if( a.result.success == 'true' ) {
ds.remove(selectedRow);
Ext.Msg.show({
title:'Confirmation',
msg: 'Data Successfully Deleted.',
buttons: Ext.Msg.OK
})
} else {
Ext.Msg.alert('Login Failed', 'Username and/or password were incorrect! Please try again!');
}
}

but firebug says that result = undefined.

everything else is still working , record will still get deleted but the message "Data Successfully Deleted" won't show up, i assume because of result=undefined.

regards,

Robin

fay
20 Sep 2007, 6:25 AM
I'm a bit confused?? Are you not talking about deleting a row and displaying a message if successful or not? What's loginForm got to do with it?

1. Using FireFox and FireBug.

* Put a breakpoint at:


if( a.result.success == 'true' ) {

* Add a watch expression for a.result, copy the value and post back here.

2. Copy the contents of your delete.php's POST's response (Console tab) and post back here.

3. Show us the contents of delete.php - is it writing back {success: true}?

robin30
20 Sep 2007, 7:13 AM
i'm very sorry, that you're confused.

let me explain it.

I have a grid with a header. In the header there is a button called 'delete row'.

when i click on a row in my grid and then press the 'delete row' button the row will get deleted from my database.

i have a waiting message that says "deleting please wait...". after it's done i get a message that says 'data deleted' and i can press ok.

this is the code for the header, button and the action when i press the button


var gridHead = grid.getView().getHeaderPanel(true);
var tb = new Ext.Toolbar(gridHead, [{
text: 'Delete Row',
handler: function() {
selectedRow = grid.getSelectionModel().getSelected();
if(selectedRow) {
gridForm.submit(
{
waitMsg: 'Deleting row, please wait...',
url:'delete.php?id='+selectedRow.data.id,
params:{rowid:selectedRow.data.id},
success: function (form, action) {
ds.remove(selectedRow);
Ext.Msg.show({
title:'Confirmation',
msg: 'Data Successfully Deleted.',
buttons: Ext.Msg.OK
})
},
failure: function(form, action) {Ext.Msg.show({
title:'Confirmation',
msg: 'Something Went Wrong, Please Try Again.',
buttons: Ext.Msg.OK,
})
}
}
);
}
}
}]);

according to you guys it's still not 100% sure that the record is deleted from my database. you suggested this


success: function (form, a) {
if( a.result.success == 'true' ) {
ds.remove(selectedRow);
Ext.Msg.show({
title:'Confirmation',
msg: 'Data Successfully Deleted.',
buttons: Ext.Msg.OK
})
} else {
Ext.Msg.alert('something went wrong! Please try again!');
}
}

if i do that firebug gives me in error: a.result is undefined
it also says

a.result has no properties
http://localhost/test/sample.js
Line 185

your #3. It takes forever to load the response on delete.php.

the record is deleted from my database but the message that the records is deleted is not showing.

Ext.Msg.show({
title:'Confirmation',
msg: 'Data Successfully Deleted.',
buttons: Ext.Msg.OK
})

this is my whole js file


var GridUI = function() {
//enable Quicktips
Ext.QuickTips.init();

//set vars
var ds; //datastore for grid
var cm; //columnModel
var grid; //component
var dsContext;
var gridForm;
var fm = Ext.form, Ed = Ext.grid.GridEditor; // shorthand alias
function formatDate(value){
return value ? value.dateFormat('Y-m-d') : '';
};
function renderStatusDisplay(value, p, r)
{
return String.format('<img id="mb4" style="cursor:pointer" src="grid/cross.png" alt="cross.png" />',value);
}
function formatBoolean(value) {
return [
'<img ', // give the checkbox image a css class of "checkbox"
'src="grid/',
value? 'checked.gif' : 'unchecked.gif',
'"/>'
].join("");
};

//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:'id',mapping:'id'},
{name: 'name', type: 'string', mapping: 'name'},
{name: 'description', type: 'string', mapping: 'description'},
{name: 'due', type: 'date', mapping: 'due'},
{name: 'amount', type: 'string', mapping: 'amount'},
{name: 'paid', type:'boolean', mapping: 'paid'},
{name: 'paid_when', type: 'date', mapping: 'paid_when'} //columnmapping
]),
filters: [
{type: 'string', dataIndex: 'name'},
{type: 'string', dataIndex: 'description'},
{type: 'date', dataIndex: 'due'},
{type: 'string', dataIndex: 'amount'},
{type: 'boolean', dataIndex: 'paid'},
{type: 'date', dataIndex: 'paid_when'}
],
});

//load datastores
ds.load();
}

//create the columnmodel
function getColumnModel() {
cm = new Ext.grid.ColumnModel([
{header: "#",
width: 30,
renderer:function(v, p, r, rowIndex, i, ds){return '' + (rowIndex+1)}
},
{
header: "Names",
dataIndex: 'name',
width: 150,
editor: new Ed(new Ext.form.ComboBox({
typeAhead: true,
triggerAction: 'all',
transform:'post',
lazyRender:true
}))
},{
header: "Description",
dataIndex: 'description',
width: 150,
editor: new Ed(new fm.TextField({
allowBlank: true,
maxLength: 50
}))
},{
header: "Due",
dataIndex: 'due',
width: 75,
renderer: formatDate,
editor: new Ed(new fm.DateField({
format: 'Y-m-d',
minValue: '2001-01-01',
}))
},{
header: "Amount",
dataIndex: 'amount',
width: 75,
renderer: Ext.util.Format.usMoney,
editor: new Ed(new fm.TextField({
allowBlank: true,
maxLength: 50
}))
},{
header: "Paid",
dataIndex: 'paid',
width: 50,
renderer: formatBoolean,
editor: new Ed(new fm.Checkbox())
},{
header: "Paid When",
dataIndex: 'paid_when',
width: 75,
renderer: formatDate,
editor: new Ed(new fm.DateField({
format: 'Y-m-d',
minValue: '2001-01-01',
}))
},
{
header: "Delete",
width: 45,
renderer: renderStatusDisplay
}
]);

//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', {
ds: ds,
cm: getColumnModel(),
enableColLock:false,
selModel: new Ext.grid.RowSelectionModel({singleSelect:false}),
clicksToEdit:2,
listeners: { // add a cellclick listener to the grid
cellclick: function(o, row, cell, e) {
// ensure mouseclick occurred within checkbox icon's visible area
if (o.getColumnModel().getDataIndex(cell) == 'paid' && e.getTarget('.checkbox', 1)) {
var rec = o.getDataSource().getAt(row);
rec.set('paid', !rec.get('paid')); // toggle "indoor" value
}
}
},
loadMask: 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, [{
text: 'Delete Row',
handler: function() {
selectedRow = grid.getSelectionModel().getSelected();
if(selectedRow) {
gridForm.submit(
{
waitMsg: 'Deleting row, please wait...',
url:'delete.php?id='+selectedRow.data.id,
params:{rowid:selectedRow.data.id},
success: function (form, a) {
if( a.result.success == 'true' ) {
ds.remove(selectedRow);
Ext.Msg.show({
title:'Confirmation',
msg: 'Data Successfully Deleted.',
buttons: Ext.Msg.OK
})
} else {
Ext.Msg.alert('something went wrong! Please try again!');
}
} ,
failure: function(form, action) {Ext.Msg.show({
title:'Confirmation',
msg: 'Something Went Wrong, Please Try Again.',
buttons: Ext.Msg.OK
})
}
}
);
}
}
}]);

var gridFoot = grid.getView().getFooterPanel(true);
var Foot = new Ext.Toolbar(gridFoot);


//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(form, action) {Ext.Msg.show({
title:'Confirmation',
msg: 'Data Successfully Saved.',
buttons: Ext.Msg.OK
})
},
failure: function(form, action) {Ext.Msg.show({
title:'Confirmation',
msg: 'Something Went Wrong, Please Try Again.',
buttons: Ext.Msg.OK,
})
}
}
);
}

//render form
gridForm.render('editGrid');
}

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

getDataSource: function() {
return ds;
}
}
}();

Ext.onReady(GridUI.init, GridUI, true);

Animal
20 Sep 2007, 7:25 AM
You need to step into the code in Firebug and look at the values.

fay
20 Sep 2007, 8:02 AM
Robin,

Show us the contents of delete.php pretty please :)

I know nothing about php but delete.php will have to echo back {success: true} or {success: false}

See: http://extjs.com/forum/showthread.php?p=63495#post63495

EDIT:

Not trying to confuse the issue, but you could also try using a Connection instead of gridForm.submit():


var conn = new Ext.data.Connection;
conn.request({
url: 'delete.php',
params: {id: selectedRow.data.id},
callback: function(options, success, response){
if (success){
}
}
});

Put a breakpoint on if (success){ and examine response. Again, your DELETE.PHP will need to write/echo a success/failure response back.

robin30
20 Sep 2007, 8:08 AM
my delete.php


<?php
mysql_connect("localhost", "blablablablabla", "blablablabla") or
die("Could not connect: " . mysql_error());
mysql_select_db("test");

$lol = $_GET['id'];
$result = "delete from `bills` where `id` = '$lol'";

$sql=mysql_query($result);
?>

fay
20 Sep 2007, 8:15 AM
Sorry Robin, but we've been saying all along, your delete.php needs to write back whether it was successful or not. In the following code, I'm just assuming it was:


<?php
mysql_connect("localhost", "blablablablabla", "blablablabla") or
die("Could not connect: " . mysql_error());
mysql_select_db("test");

$lol = $_GET['id'];
$result = "delete from `bills` where `id` = '$lol'";

$sql=mysql_query($result);

echo "{success:true}";
?>

robin30
20 Sep 2007, 8:25 AM
somewhere in the forum i saw


a = "{success: true}";

if i use this in my js file

success: function (form, a) {
if( a = {success: true} ) {
ds.remove(selectedRow);
Ext.Msg.show({
title:'Confirmation',
msg: 'Data Successfully Deleted.',
buttons: Ext.Msg.OK
})
GridUI.getDataSource().reload()
} else {
Ext.Msg.alert('Something Went Wrong! Please try again!');
}
}

firebug does not give an error.

so it works?

robin30
20 Sep 2007, 8:26 AM
ops, sorry, read it wrong. thanks guys

robin30
20 Sep 2007, 10:05 AM
because of all the testing with deleting records. i deleted all my record in the database through the grid. because there are no more records in my database the grid won't load anymore.

loadingmask keeps loading and loading.

so all i have to do is to add

echo"{success:true}";

to my php file for the grid (called sample.php)?

just don't know where to put it.

this is my php file for the grid (where the grid gets all it's information on what records to show from my database).


<?php

//make database connection
mysql_connect("localhost", "blablablabla", "blablablablablablabla") or
die("Could not connect: " . mysql_error());
mysql_select_db("test");

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 = "SELECT * FROM bills order by id DESC";
$sql = $result . " LIMIT ". (int) $_POST['start'].", ". (int) $_POST['limit'];
$lol=mysql_query($result);
$rows = mysql_num_rows($lol);

while($rec = mysql_fetch_array($lol)){
$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 bills");

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 `bills` SET `name` = '$value' WHERE `id`='$id[$row]';");
if($field=='description') //the field name is being updated
$result = mysql_query("UPDATE `bills` SET `description` = '$value' WHERE `id`='$id[$row]';");
if($field=='due') //the field name is being updated
$result = mysql_query("UPDATE `bills` SET `due` = '$value' WHERE `id`='$id[$row]';");
if($field=='amount') //the field name is being updated
$result = mysql_query("UPDATE `bills` SET `amount` = '$value' WHERE `id`='$id[$row]';");
if($field=='paid') //the field name is being updated
$result = mysql_query("UPDATE `bills` SET `paid` = '$value' WHERE `id`='$id[$row]';");
if($field=='paid_when') //the field name is being updated
$result = mysql_query("UPDATE `bills` SET `paid_when` = '$value' WHERE `id`='$id[$row]';");
}
?>

robin30
20 Sep 2007, 10:08 AM
instead of putting

echo"{success:true}";
somewhere

i did this

$result = "SELECT * FROM bills order by id DESC";
$sql = $result . " LIMIT ". (int) $_POST['start'].", ". (int) $_POST['limit'];
$lol=mysql_query($result);
$rows = mysql_num_rows($lol);
if ($rows==''){
echo"{success:false}";
} else {
while($rec = mysql_fetch_array($lol)){
$arr[] = $rec;

}
echo $_GET['callback'].'({"total":"'.$rows.'","results":'.json_encode($arr).'})';
}

and it seems to work,

Thank you guys for you patience and for helping me, really appreciate it

thejdog
20 Sep 2007, 10:14 AM
yea but is your php file spitting back to the script {success: true} so that it knows that it actually did go successfully?

robin30
20 Sep 2007, 11:19 AM
hi thejdog,

according to firebug under response it says:

{success:true}

so i assume yes

and if i still see it wrong, forgive me.

because then i'm really lost and really don't know what you mean.

Animal
20 Sep 2007, 11:39 AM
$_GET['callback'].'(...


Are you using a ScriptTagProxy with this code?

robin30
20 Sep 2007, 1:03 PM
at the top of my js file yes, it says


proxy: new Ext.data.ScriptTagProxy({
url: 'sample.php?ac=showData' //a function in your php-script must be activated when ac = showdata
}),

but the deletion of the records is not going through sample.php but through delete.php.

the base for my grid is from the example, edit-grid.