How to setup login/register in ionic3 using PHP, MySQL

Posted on Posted in Beginner

In this tutorial we are going to look at how to setup  login and register in ionic3 using PHP and MySQL, to achieve this, we will need to do the following

  1. Create an app (loginRegisterApp)
  2. Create the login and register html pages
  3. Create a table in our database
  4. Create login and register php files
  5. Write methods for login and register
  6. Test our app

If you are ready, I am ready




  1. Create an app (loginRegisterApp)

Change to command prompt and type the code below to create an app in ionic

ionic start loginRegisterApp blank

Type Y at the prompt  Would you like to integrate your new app with Cordova to target native iOS and Android? (y/N) y and press enter key

ionic don php_mysql

Done?

Change directory to our newly created app = loginRegisterApp and run your app

                ionic serve –l

Phew!!!, do you have what I have below?

ionic don php_mysql

WELL DONE




 

2.  Create the login and register html pages

Open you code editor and change the ion-title to Login and change the contents between <ion-content> </ion-content> tag to the code below

<ion-list no-lines>

    <ion-item  >

      <ion-input  round type=”text” placeholder=”Username” name=”username” #username></ion-input>

    </ion-item>

    <ion-item>

      <ion-input type=”password” placeholder=”Password” name=”password” #password></ion-input>

    </ion-item>

    <button ion-button round block (click)=”signIn()”>Sign In</button>

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

  </ion-list>

 

Save and run your app again, are we on the same page? See below to confirm

ionic don mysql_php

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

ionic don, php mysql




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

  1. Import RegisterPage from its location
  2. Add RegisterPage 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)

ionic don app.modules.ts

Now, open your register.html and insert the following code between <ion-content> </ion-content> tag

<ion-list no-line>

    <ion-item>

      <ion-input type=”text” placeholder=”Username” name=”fullname” #username></ion-input>

    </ion-item>

      <ion-item>

      <ion-input type=”email” placeholder=”Email” name=”email” #email></ion-input>

    </ion-item>

      <ion-item>

      <ion-input type=”number” placeholder=”Mobile Number” name=”mobile” #mobile></ion-input>

    </ion-item>

    <ion-item>

      <ion-input type=”password” placeholder=”Password” name=”password” #password></ion-input>

    </ion-item>

  </ion-list>

  <div padding>

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

  </div>

Finally for this section, let’s write a method to navigate to register page from home(login) page, to achieve this add the following code to home.ts under constructor

 

signUp(){

  this.navCtrl.push(RegisterPage);

  }

Don’t forget to import Register page into home.ts by adding the following code to the top of the page

import { RegisterPage} from ‘../register/register’;

Your register page should look like this

ionic don register page




 

3. Create a table in our database

Now, let head to our database and create a table called users with the following column and data type:

  • Id – int(11)
  • Username – varchar(255)
  • Password – varchar(255)
  • Telephone – varchar(25)
  • Email – varchar(50)

as shown below

ionic don myphpadmin

 

4.  Create login and register php files

In this section, we are going to create three(3) files namely

  • php to connect our app to the database
  • php to executive login process
  • php to register a new user

Open your favorite text editor, open a new file and add the following code

<?php

  define(‘HOST’,’localhost’);

  define(‘USER’,’your_user_name’);

  define(‘PASS’,’your_password);

  define(‘DB’,database_name’);

  $con = mysqli_connect(HOST,USER,PASS,DB);

   if (!$con){

                 die(“Error in connection” . mysqli_connect_error()) ;

  }

?>

Save this file as dbconnect.php




Open another new file and add the following code

<?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);

        $username = $request->username;

        $password = $request->password;

                }

      $username= mysqli_real_escape_string($con,$username);

      $password = mysqli_real_escape_string($con,$password);

       $username = stripslashes($username);

      $password = stripslashes($password);

    $sql = “SELECT id FROM users WHERE username = ‘$username’ and password = ‘$password'”;

      $result = mysqli_query($con,$sql);

      $row = mysqli_fetch_array($result,MYSQLI_ASSOC);

      $active = $row[‘active’];

      $count = mysqli_num_rows($result);

     

      // If result matched myusername and mypassword, table row must be 1 row                    

      if($count >0) {

     $response= “Your Login success”;

      }else {

    $response= “Your Login Email or Password is invalid”;         

      }

 echo json_encode( $response);

?>

Save this file as login.php.

And now the last but not the least file, open a new file and the code below

<?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);

        $emailadd = $request->email;

          $password = $request->password;

           $username = $request->username;

          $mobile = $request->mobile;

                                }

$username = stripslashes($username);

$password = stripslashes($password);

$sql = “INSERT INTO users (name, password, email, telephone)

VALUES (‘$name’, ‘$password’, ‘$emailadd’, ‘$mobile’)”;

if ($con->query($sql) === TRUE) {

                $response= “Registration successfull”;

} else {

   $response= “Error: ” . $sql . “<br>” . $db->error;

}

 echo json_encode( $response);

?>

Save the file as register.php.

Finally, upload the files into your online server.




 

5.  Write methods for login and register

Now, let’s head back to our ionic app, open home.ts, change the content to the code below

import { Component, ViewChild  } from ‘@angular/core’;

import { NavController, AlertController} from ‘ionic-angular’;

import { RegisterPage } from ‘../register/register’;

import {Http, Headers, RequestOptions}  from “@angular/http”;

import { LoadingController } from ‘ionic-angular’;

import ‘rxjs/add/operator/map’;

@Component({

selector: ‘page-home’,

templateUrl: ‘home.html’

})

export class HomePage {

@ViewChild(“username”) username;

@ViewChild(“password”) password;

data:string;

constructor(public navCtrl: NavController, public alertCtrl: AlertController,

private http: Http, public loading: LoadingController) {

}

signUp(){

this.navCtrl.push(RegisterPage);

}

signIn(){

//// check to confirm the username and password fields are filled

if(this.username.value==”” ){

let alert = this.alertCtrl.create({

title:”ATTENTION”,

subTitle:”Username field is empty”,

buttons: [‘OK’]

});

alert.present();

} else

if(this.password.value==””){

let alert = this.alertCtrl.create({

title:”ATTENTION”,

subTitle:”Password field is empty”,

buttons: [‘OK’]

});

alert.present();

}

else

{

var headers = new Headers();

headers.append(“Accept”, ‘application/json’);

headers.append(‘Content-Type’, ‘application/json’ );

let options = new RequestOptions({ headers: headers });

let data = {

username: this.username.value,

password: this.password.value

};

let loader = this.loading.create({

content: ‘Processing please wait…’,

});

loader.present().then(() => {

this.http.post(‘http://ionicdon.com/mobile/login.php’,data,options)

.map(res => res.json())

.subscribe(res => {

console.log(res)

loader.dismiss()

if(res==”Your Login success”){

let alert = this.alertCtrl.create({

title:”CONGRATS”,

subTitle:(res),

buttons: [‘OK’]

});

alert.present();

}else

{

let alert = this.alertCtrl.create({

title:”ERROR”,

subTitle:”Your Login Username or Password is invalid”,

buttons: [‘OK’]

});

alert.present();

}

});

});

}

}

}

 

Also change the content of register.ts to the code below

import { Component, ViewChild } from ‘@angular/core’;

import { NavController, AlertController } from ‘ionic-angular’;

import { HomePage } from ‘../home/home’;

import {Http, Headers, RequestOptions}  from “@angular/http”;

import { LoadingController } from ‘ionic-angular’;

import ‘rxjs/add/operator/map’;

@Component({

selector: ‘page-register’,

templateUrl: ‘register.html’

})

export class RegisterPage {

@ViewChild(“email”) email;

@ViewChild(“username”) username;

@ViewChild(“mobile”) mobile;

@ViewChild(“password”) password;

constructor(public navCtrl: NavController, public alertCtrl: AlertController,  private http: Http,  public loading: LoadingController) {

}

Register(){

//// check to confirm the username, email, telephone and password fields are filled

if(this.username.value==”” ){

let alert = this.alertCtrl.create({

title:”ATTENTION”,

subTitle:”Username field is empty”,

buttons: [‘OK’]

});

alert.present();

} else

if(this.email.value==””){

let alert = this.alertCtrl.create({

title:”ATTENTION”,

subTitle:”Email field is empty”,

buttons: [‘OK’]

});

alert.present();

}

else

if(this.mobile.value==”” ){

let alert = this.alertCtrl.create({

title:”ATTENTION”,

subTitle:”Mobile number field is empty”,

buttons: [‘OK’]

});

alert.present();

} else

if(this.password.value==””){

let alert = this.alertCtrl.create({

title:”ATTENTION”,

subTitle:”Password field is empty”,

buttons: [‘OK’]

});

alert.present();

}

else

{

var headers = new Headers();

headers.append(“Accept”, ‘application/json’);

headers.append(‘Content-Type’, ‘application/json’ );

let options = new RequestOptions({ headers: headers });

let data = {

username: this.username.value,

password: this.password.value,

mobile: this.mobile.value,

email: this.email.value

};

let loader = this.loading.create({

content: ‘Processing please wait…’,

});

loader.present().then(() => {

this.http.post(‘http://ionicdon.com/mobile/register.php’,data, options)

.map(res => res.json())

.subscribe(res => {

loader.dismiss()

if(res==”Registration successfull”){

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();

}

});

});

}

}

}

 

 

6.  Test our app

We are done, quiet interesting, isn’t it? Now let’s test our app, go to command prompt, change directory to your app folder and type

ionic serve –l

52 thoughts on “How to setup login/register in ionic3 using PHP, MySQL

  1. Hi Hicham,
    confirm that your system has internet connection, this could be a reason, otherwise it works fine

  2. Thanks , I have recently been searching for info about this topic for ages and yours is the best I’ve found out till now. But, what concerning the bottom line? Are you sure about the source?

  3. Definitely, what a splendid blog and illuminating posts, I surely will bookmark your site.All the Best!

        1. i am experiencing the same issue .. if i use your Url everything works fine. if i replaceit with my url then.. it hangs at the loader. kindly assist.

      1. Check that your url is updated in home.ts and register.ts files to your new url, it works fine for me, kudos to ionic don

  4. Sorry, but on my computer it doesn’t work.
    App doesn’t start. Runtime Error Uncaught (in promise): Error:StaticInjectorError(AppModule)[HomePage->Http]: StaticIncetorError(Platform:core)[HomePage->Http]:NullInjectorError:No provier for Http

    1. Hi Alex,

      you will need to import HttpClientModule and HttpModule in app.module.ts file as shown below

      import { HttpClientModule } from ‘@angular/common/http’;
      import { HttpModule } from ‘@angular/http’;

      and add them to imports section of the same app.module.ts file as also shown below
      imports: [
      BrowserModule,
      HttpClientModule,
      HttpModule,

      IonicModule.forRoot(MyApp)
      ],

      I hope it helps and if you are still not clear, see my tutorial on How to write, read and display data from MySQL database in ionic app and check the image on app.modulle.ts

  5. hi
    i followed the steps but i am getting an error in both the SQL statements. as shown below. if i use my URL.
    Notice: Trying to get property of non-object in /storage/ssd2/639/1910639/public_html/loginRegisterApp/login.php on line 37
    if i use your URL then it works fine. kindly share your SQL statement again.

    1. Hi Lawrence,

      The database and tables were created manually, check the table field and confirmed they have the same name as what you have in your code and confirm that you dbconnect.php file actually connect to your database

          1. Where is fetch data in this tutorial?? The follow on series is not right for this, it includes a config.php file and a $db variable when we use $con here also array I’d is different, can you please upload FULL files to github or sort the tutorial out please?

  6. hi, I get an error in my register php it says: Notice: Trying to get property of non-object. Also I have an error “Unexpected token < in JSON at position 0"

    1. Hello,
      Did you get a fix for this. I have the same issue. I’m using a PHP app engine service on google cloud. ionicdon.com works fine so client code is ok but not my own backend!!

  7. i really love this tutorial and success to adapted it. My question is what if we want to added some localstorage into this apps.
    i have tried it. i have success on set some key to localstorage.

    my idea to use localstorage is when user already login then there is no need to show login page we can pass it and go to profile page directly.

    but i can to get localstorage it can be show that my profile page just blank with no fetch data.

    Can you show me how to that??

    regards,

  8. Thanks for tutorial, it’s getting me in the right direction. I have a CORS problem however and I can’t seem to get around it!
    When I call my login.php script I get the following:

    Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

    I’ve used the same login.php as you and http://ionicdon.com/mobile/login.php works fine so it must be an environmental thing with my service. I’m using a PHP service on google’s app engine.

    Appreciate if you have any idea how to resolve! Thanks

  9. How can validation of email or username or mobile format be done (on client side before/without sending request to server) in this same code?

  10. Man so many errors. some fields are wrong on insert queries missing code in the ionic app too.
    also your site converts double quotes to different double quotes
    and you post the code in a hard to read non code formatted blue text.
    have your really tested what you written or not? I even gone through your repo to check the codes but IDK after some changes I tracked errors in the register php file
    for example
    $emailadd = $request->email;
    these return trying to get property of non object I am not a pro but trying and failing so many times doesn’t feel good.
    Get back to me on my mail to discuss about stuff

  11. Hi, I have a problem.
    ‘@ angular / http’ is in disuse
    currently used ‘@ angular / common / http’
    my problem is in the
    import {RequestOptions} from “@ angular / http”;
    I see the incompatibility error.
    I already made the changes in (headers to httpheaders) and (http to HttpClient). With these two I no longer have problems.
    the RequestOptions is the one that says incompatible
    I hope you help me with that modification.

  12. please i try this example but have and error when i try to register or log in:
    this is the error:
    ERROR SyntaxError: “JSON.parse: unexpected character at line 1 column 1 of the JSON data”

    please can someone help me with the solution??

  13. I blog frequently and I really thank you for your content.
    Your article has really peaked my interest. I am going to book mark your blog
    and keep checking for new details about once per week.
    I opted in for your RSS feed as well.

  14. Wonderful blog! I found it while surfing around on Yahoo News.
    Do you have any tips on how to get listed in Yahoo News?

    I’ve been trying for a while but I never seem to get there!
    Appreciate it

  15. hi. why I still got error when Im trying to login.
    Unexpected token < in JSON at position 0.

    And when I click the url using my own url, got error like this.
    Notice: Trying to get property of non-object in C:\xampp\htdocs\esiasattest\sidemenu\login.php on line 25

    Notice: Trying to get property of non-object in C:\xampp\htdocs\esiasattest\sidemenu\login.php on line 26

    Notice: Undefined index: active in C:\xampp\htdocs\esiasattest\sidemenu\login.php on line 35

  16. Great web site you’ve got here.. It’s difficult to find high quality writing like yours
    nowadays. I seriously appreciate people like you!

    Take care!!

  17. In my case I do not know what is missing, or what is wrong, when placing a specific login and password registered in the database by the app, it returns me user and password of a totally different login, I think POST is not working .. .how can I solve?

    1. Hi Gustavo,
      Though your question is beyond the scope of this tutorial, because this tutorial covers just login/register and does not return any value except login valid or invalid.

      All the same, what could be wrong is the username uniqueness in the database, you might need to provide a mechanism to make sure your user’s username are unique by comparing the username with the usernames already in the database. reject the username if already exist or accept registration if it is unique. that would ensure return of desired login credentials and other info of the login users.

      Happy coding

      1. I found out, that’s right, the post is not getting the login and password entered, so the login and password that it returns to me is the first record of the database

Leave a Reply

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