This tutorial is a continuation of my earlier post How to write, read and display data from MySQL database in ionic app, in this tutorial, we are going to learn how to edit and delete data displayed in ionic app from MySQL database.
Prerequisite
It is very important you complete the first part of this tutorial before proceeding further because it is a continuation and most files and the database were created and populated in the said tutorial.
To achieve our today’s task, we need to do the following
- Modify home.html to display delete and edit icon
- Create a new page called edit page
- Create edit page user interface
- Write a method to update database with new input
- Create a new php file to edit database called edit_data.php
- Write a method to navigate to edit page from the home page
- Write a method to delete data
- Create a php file called delete_data.php to delete data from database
If you are ready, Let’s GO!!
- Modify home.html to display delete and edit icon
Open home.html and change the code between <ion-content> </ion-content> tag to the following
[cc]
Country
Capital
{{item.country}}
{{item.capital}}
[/cc]
Save the file and run your app, you should have what I have below
Are we on the same page?? If yes, congratulations, let’s proceed to step 2.
- Create a new page called edit page
Now, let’s create edit page, from CLI as shown below
Now, open app.modules.ts under src/app/ and do the following
- Import EditPage from its location
- Add EditPage to declaration and entryComponents section
Your app.module.ts will look like this ( see How To Navigate Between Pages In Ionic 2+ Application
For details)
3. Create edit page user interface
Open edit.html, insert the following code between <ion-content> </ion-content> tag
[cc]
Country
Capital
[/cc]
- Write a method to update database with new input
In this step we are going to write a method to update our database, to achieve this we need to do the following
- Collect data from the previous page using NavParams as our page initialized and assign to variable as shown below
ngOnInit(){
this.country = this.params.get(‘country’) ;
this.capital = this.params.get(‘capital’) ;
this.oldCountryValue = this.params.get(‘country’) ;
this.oldCapitalValue = this.params.get(‘capital’) ;
}
2.Check to see that the edited row is not replaced with blank using conditional statement as thus:
if(this.newCountry.value==”” ){
let alert = this.alertCtrl.create({
title:”ATTENTION”,
subTitle:”Country field is empty”,
buttons: [‘OK’]
});
alert.present();
} else
if(this.newCapital.value==””){
let alert = this.alertCtrl.create({
title:”ATTENTION”,
subTitle:”Capital field is empty”,
buttons: [‘OK’]
});
alert.present();
}
3.Use http post method to send old data and new data to the server, then set navigation back to the home page if the update is successful as shown below
var headers = new Headers();
headers.append(“Accept”, ‘application/json’);
headers.append(‘Content-Type’, ‘application/json’ );
let options = new RequestOptions({ headers: headers });
let data = {
country: this.oldCountryValue,
capital: this.oldCapitalValue,
newCountry: this.newCountry.value,
newCapital: this.newCapital.value,
};
let loader = this.loading.create({
content: ‘Processing please wait…’,
});
loader.present().then(() => {
this.http.post(‘http://localhost/ionicdon_local/edit_data.php’,data, options)
.map(res => res.json())
.subscribe(res => {
loader.dismiss()
if(res==”data updated successfully”){
let alert = this.alertCtrl.create({
title:”CONGRATS”,
subTitle:(res),
buttons: [‘OK’]
});
alert.present();
this.navCtrl.push(HomePage);
}else
{
let alert = this.alertCtrl.create({
title:”ERROR”,
subTitle:(res),
buttons: [‘OK’]
});
alert.present();
}
At the end, our edit.ts page will finally look like what I have below
5.Create a new php file to edit database called edit_data.php
Open your favourite code editor, enter the following code and save as edit_data.php
<?php
if (isset($_SERVER[‘HTTP_ORIGIN’])) {
header(“Access-Control-Allow-Origin: {$_SERVER[‘HTTP_ORIGIN’]}”);
header(‘Access-Control-Allow-Credentials: true’);
header(‘Access-Control-Max-Age: 86400’); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER[‘REQUEST_METHOD’] == ‘OPTIONS’) {
if (isset($_SERVER[‘HTTP_ACCESS_CONTROL_REQUEST_METHOD’]))
header(“Access-Control-Allow-Methods: GET, POST, OPTIONS”);
if (isset($_SERVER[‘HTTP_ACCESS_CONTROL_REQUEST_HEADERS’]))
header(“Access-Control-Allow-Headers: {$_SERVER[‘HTTP_ACCESS_CONTROL_REQUEST_HEADERS’]}”);
exit(0);
}
require “dbconnect.php”;
$data = file_get_contents(“php://input”);
if (isset($data)) {
$request = json_decode($data);
$country = $request->country;
$capital = $request->capital;
$newCountry = $request->newCountry;
$newCapital = $request->newCapital;
}
$sql = “UPDATE countries SET capital = ‘$newCapital’, country =’$newCountry’ WHERE capital =’$capital’;”;
if ($con->query($sql) === TRUE) {
$response= “data update successfull”;
} else {
$response= “Error: ” . $sql . “<br>” . $con->error;
}
echo json_encode( $response);
$con->close();
?>
6. Write a method to navigate to edit page from the home page
Open home.ts , add the following code to the existing code
editPost(item){
this.navCtrl.push(EditPage, item)
}
7. Write a method to delete data
While still in home.ts page, add following code
deletePost(item) {
let alert = this.alertCtrl.create({
title: ‘Confirm delete’,
message: ‘Do you really want to delete this row?’,
buttons: [
{
text: ‘Cancel’,
role: ‘cancel’,
handler: () => {
console.log(‘Cancel clicked’);
}
},
{
text: ‘Delete’,
handler: () => {
//this.navCtrl.push(DeletePage, item)
var headers = new Headers();
headers.append(“Accept”, ‘application/json’);
headers.append(‘Content-Type’, ‘application/json’ );
let options = new RequestOptions({ headers: headers });
let loader = this.loading.create({
content: ‘Processing please wait…’,
});
loader.present().then(() => {
this.http.post(‘http://ionicdon.com/mobile/delete_data.php’, item, options)
.map(res => res.json())
.subscribe(res => {
loader.dismiss()
if(res==”data deleted successfully”){
let alert = this.alertCtrl.create({
title:”CONGRATS”,
subTitle:(res),
buttons: [‘OK’]
});
alert.present()
this.navCtrl.push(HomePage);
}else
{
let alert = this.alertCtrl.create({
title:”ERROR”,
subTitle:(res),
buttons: [‘OK’]
});
alert.present();
}
});
});
}
}
]
});
alert.present();
}
In the above code, we first of all confirm deletion, this is a very important and precautionary method of making sure data is not deleted mistakenly, by using alert box.
Then, use http post method to post the data to be deleted to the server.
At the end, our home.ts will look like below
8. Create a php file called delete_data.php to delete data from database
Open your favourite editor and key in the following
<?php
if (isset($_SERVER[‘HTTP_ORIGIN’])) {
header(“Access-Control-Allow-Origin: {$_SERVER[‘HTTP_ORIGIN’]}”);
header(‘Access-Control-Allow-Credentials: true’);
header(‘Access-Control-Max-Age: 86400’); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER[‘REQUEST_METHOD’] == ‘OPTIONS’) {
if (isset($_SERVER[‘HTTP_ACCESS_CONTROL_REQUEST_METHOD’]))
header(“Access-Control-Allow-Methods: GET, POST, OPTIONS”);
if (isset($_SERVER[‘HTTP_ACCESS_CONTROL_REQUEST_HEADERS’]))
header(“Access-Control-Allow-Headers: {$_SERVER[‘HTTP_ACCESS_CONTROL_REQUEST_HEADERS’]}”);
exit(0);
}
require “dbconnect.php”;
$data = file_get_contents(“php://input”);
if (isset($data)) {
$request = json_decode($data);
$country = $request->country;
$capital = $request->capital;
}
$country = stripslashes($country);
$capital = stripslashes($capital);
$sql = “DELETE FROM countries WHERE country =’$country’;”;
if ($con->query($sql) === TRUE) {
$response= “data deleted successfull”;
} else {
$response= “Error: ” . $sql . “<br>” . $con->error;
}
echo json_encode( $response);
$con->close();
?>
Save the file as delete_data.php
9. Test your app
If you have followed through to this point, give yourself a nod. Now, upload your php files to your server.
Change to command prompt and issue the following command
ionic serve –l
check the video below to see if your own app runs the same way
if you find the tutorial useful, don’t forget to bless others by sharing it
Pingback: How to write, read and display data from MySQL database in ionic app - Ionic Don
Tolu Faleye
16 Aug 2018Thank you ionic don, this is one out of a million, your tutorial is apt and loaded, keep it up
Golden
19 Aug 2018i remember i’m the 1 who requested this thank you alot brother, God bless you
Sam
20 Aug 2018Great! Thank you
But how do i link this to a user using that login and register tutorial
Laide Lawal
23 Aug 2018@Sam, can you expatiate further, I don’t understand what you mean
Sam
25 Aug 2018like after logged in, the user can upload, edit and delete own data
Laide Lawal
26 Aug 2018It follows the same process, adapt the same principle I discussed in the two tutorials to do whatever you wish
Gonzalo
25 Sep 2018excellent input but I get the following error in the php files:
Notice: Trying to get property of non-object in C:\xampp\htdocs\login\delete_data.php on line 41
Notice: Trying to get property of non-object in C:\xampp\htdocs\login\delete_data.php on line 42
Notice: Trying to get property of non-object in C:\xampp\htdocs\login\delete_data.php on line 43
Notice: Trying to get property of non-object in C:\xampp\htdocs\login\delete_data.php on line 44
“data deleted successfull”
please help me find the solution!!!
Gonzalo
25 Sep 2018Excellent contribution but this error is coming out in the php files:
Notice: Trying to get property of non-object in C:\xampp\htdocs\login\delete_data.php on line 41
Notice: Trying to get property of non-object in C:\xampp\htdocs\login\delete_data.php on line 42
Notice: Trying to get property of non-object in C:\xampp\htdocs\login\delete_data.php on line 43
Notice: Trying to get property of non-object in C:\xampp\htdocs\login\delete_data.php on line 44
“data deleted successfull”
please help me find the solution!!!