How to edit and delete displayed data from MySQL database in ionic app

Posted on Posted in Beginner

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

  1. Modify home.html to display delete and edit icon
  2. Create a new page called edit page
  3. Create edit page user interface
  4. Write a method to update database with new input
  5. Create a new php file to edit database called edit_data.php
  6. Write a method to navigate to edit page from the home page
  7. Write a method to delete data
  8. Create a php file called delete_data.php to delete data from database

If you are ready, Let’s GO!!




 

  1. 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

<button ion-button  round outline block (click)=”Post()”>Post</button>

  <ion-row class= “header”>

      <ion-col col-4>

        Country

      </ion-col>

      <ion-col col-4>

        Capital

      </ion-col>

      <ion-col col-4>

      </ion-col>

  </ion-row>

  <ion-item *ngFor=”let item of items” >

  <ion-row>

    <ion-col col-4>

      {{item.country}}

    </ion-col>

    <ion-col col-4>

      {{item.capital}}

    </ion-col>

    <ion-col col-2>

      <ion-icon name=”create” (click)=”editPost(item)”></ion-icon>

        </ion-col>

        <ion-col col-2>

          <ion-icon name=”close” (click)=”deletePost(item)”></ion-icon>

            </ion-col>

</ion-row>

 </ion-item>

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.

  1. Create a new page called edit page

Now, let’s create profile page, from CLI as shown below

Now, open app.modules.ts under src/app/  and do the following

  1. Import EditPage from its location
  2. 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

<ion-list no-line>

        <ion-item>

            <ion-label floating>Country</ion-label>

            <ion-input id=”newCountry” type=”text” name= “newCountry” #newCountry [(ngModel)]=”country”></ion-input>

          </ion-item>

          <ion-item>

              <ion-label floating>Capital</ion-label>

              <ion-input id=”newCapital” type=”text” name= “newCapital” #newCapital [(ngModel)]=”capital”></ion-input>

            </ion-item>

      </ion-list>

      <div >

      <button ion-button  round outline block (click)=”Edit()”>Update</button>

      </div>

 




  1. 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

  1. 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




9 thoughts on “How to edit and delete displayed data from MySQL database in ionic app

  1. excellent 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!!!

  2. Excellent 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!!!

Leave a Reply

Your email address will not be published. Required fields are marked *