Simplified iOS

  • Home
  • About
  • Contact
  • Advertise
  • Write for Us

iOS Registration Form Example using PHP and MySQL

February 5, 2017 by Belal Khan 22 Comments

In this post we will see an iOS Registration Form Example. A user registration and login screen is a very essential thing in many application. Thats why I am posting this iOS Registration Form Example. In the next post we will see iOS Login Example.

I am going to use PHP and MySQL as application’s backend. And we will use Swift Programming in XCode. We already learnt about connecting iOS App to MySQL database, in one of the previous tutorials. You can check the tutorial from the below link.

Connecting iOS App to MySQL Database

In this post we will use the same concept but this time for networking operations I will be using Alamofire. If you don’t know what it is then don’t worry just keep reading.

Contents

  • 1 iOS User Registration Video Tutorial
  • 2 Building Server Side Scripts and Database
    • 2.1 Building Database
    • 2.2 Building Web Service
      • 2.2.1 Creating a PHP Project
      • 2.2.2 Constants.php
      • 2.2.3 DbConnect.php
      • 2.2.4 DbOperation.php
      • 2.2.5 register.php
      • 2.2.6 Testing Web Service
  • 3 iOS Registration Form Example
    • 3.1 Creating a new XCode Project
      • 3.1.1 Adding Alamofire
      • 3.1.2 Creating Interface
      • 3.1.3 Connecting Views with Code
      • 3.1.4 Adding User Registration
      • 3.1.5 Testing the Application
      • 3.1.6 Download Source Code
    • 3.2 Share this:
    • 3.3 Related

iOS User Registration Video Tutorial

  • You can also watch this video tutorial to know how to build this app.

Building Server Side Scripts and Database

Building Database

  • First we need a database. So I have the following database.

users table

  • For creating the above Table you can use the following query.
-- tables
-- Table: users
CREATE TABLE users (
    id int  NOT NULL PRIMARY KEY AUTO_INCREMENT,
    username varchar(100)  NOT NULL,
    password text  NOT NULL,
    email varchar(100)  NOT NULL,
    name varchar(100)  NOT NULL,
    phone varchar(10)  NOT NULL
);

-- End of file.
  • Executing the above query will create the following table.

users table structure

Building Web Service

  • Now we need a Web Service that will act as a medium of communication between our application and database. Again I am using very simple method to do this. But you can also check the recommended method of Building a REST API on this link.

Creating a PHP Project

  • The first step is creating a new project. I am using PHP Storm, you can use any IDE you like or a normal source code editor like sublime or notepad++ will also be good enough.

php project

  • Now inside your project you have to create two directories named includes and v1. Inside includes create three php files Constants.php, DbConnect.php, DbOperation.php and inside v1 create register.php. (See the screenshot below for help).

project structure

Constants.php

  • Open Constants.php and write the following code. The file is containing the required constants.
<?php
/**
 * Created by PhpStorm.
 * User: Belal
 * Date: 04/02/17
 * Time: 7:50 PM
 */

define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'simplifiedios');

define('USER_CREATED', 0);
define('USER_ALREADY_EXIST', 1);
define('USER_NOT_CREATED', 2);

DbConnect.php

  • This file will connect to the database and will return a connection link.
<?php

/**
 * Created by PhpStorm.
 * User: Belal
 * Date: 04/02/17
 * Time: 7:51 PM
 */
class DbConnect
{
    private $conn;

    function __construct()
    {
    }

    /**
     * Establishing database connection
     * @return database connection handler
     */
    function connect()
    {
        require_once 'Constants.php';

        // Connecting to mysql database
        $this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

        // Check for database connection error
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        // returing connection resource
        return $this->conn;
    }
}

DbOperation.php

  • This file will handle all the database operations. Right now we have to only insert the user data to the table.
<?php

/**
 * Created by PhpStorm.
 * User: Belal
 * Date: 04/02/17
 * Time: 7:51 PM
 */
class DbOperation
{
    private $conn;

    //Constructor
    function __construct()
    {
        require_once dirname(__FILE__) . '/Constants.php';
        require_once dirname(__FILE__) . '/DbConnect.php';
        // opening db connection
        $db = new DbConnect();
        $this->conn = $db->connect();
    }

    //Function to create a new user
    public function createUser($username, $pass, $email, $name, $phone)
    {
        if (!$this->isUserExist($username, $email, $phone)) {
            $password = md5($pass);
            $stmt = $this->conn->prepare("INSERT INTO users (username, password, email, name, phone) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("sssss", $username, $password, $email, $name, $phone);
            if ($stmt->execute()) {
                return USER_CREATED;
            } else {
                return USER_NOT_CREATED;
            }
        } else {
            return USER_ALREADY_EXIST;
        }
    }


    private function isUserExist($username, $email, $phone)
    {
        $stmt = $this->conn->prepare("SELECT id FROM users WHERE username = ? OR email = ? OR phone = ?");
        $stmt->bind_param("sss", $username, $email, $phone);
        $stmt->execute();
        $stmt->store_result();
        return $stmt->num_rows > 0;
    }
}

register.php

  • Now this is the main script where we will send the request to register a new user.
<?php
/**
 * Created by PhpStorm.
 * User: Belal
 * Date: 04/02/17
 * Time: 7:51 PM
 */

//importing required script
require_once '../includes/DbOperation.php';

$response = array();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!verifyRequiredParams(array('username', 'password', 'email', 'name', 'phone'))) {
        //getting values
        $username = $_POST['username'];
        $password = $_POST['password'];
        $email = $_POST['email'];
        $name = $_POST['name'];
        $phone = $_POST['phone'];

        //creating db operation object
        $db = new DbOperation();

        //adding user to database
        $result = $db->createUser($username, $password, $email, $name, $phone);

        //making the response accordingly
        if ($result == USER_CREATED) {
            $response['error'] = false;
            $response['message'] = 'User created successfully';
        } elseif ($result == USER_ALREADY_EXIST) {
            $response['error'] = true;
            $response['message'] = 'User already exist';
        } elseif ($result == USER_NOT_CREATED) {
            $response['error'] = true;
            $response['message'] = 'Some error occurred';
        }
    } else {
        $response['error'] = true;
        $response['message'] = 'Required parameters are missing';
    }
} else {
    $response['error'] = true;
    $response['message'] = 'Invalid request';
}

//function to validate the required parameter in request
function verifyRequiredParams($required_fields)
{

    //Getting the request parameters
    $request_params = $_REQUEST;

    //Looping through all the parameters
    foreach ($required_fields as $field) {
        //if any requred parameter is missing
        if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {

            //returning true;
            return true;
        }
    }
    return false;
}

echo json_encode($response);

Testing Web Service

  • Now lets test it is working or not. You can use any REST Client extension I am using POSTMAN.

iOS Registration Form Example

  • As you can see it is working fine. Also check the database whether the values are inserted or not.

iOS Registration Form Example

  • Now its time to start our XCode Project.

Creating a new XCode Project

  • Create a Single View application.
  • Now close the project as we need to Add Alamofire. For this we will use Cocoapods. If you don’t know about it check the Firebase iOS Tutorial where I have explained about cocoa pods in detail.

Adding Alamofire

  • Open terminal and navigate to your Xcode Project Directory.
  • Now right the following command.
pod init
  • The above command will create a podfile inside your project folder. Open the file and replace the content with the following.
# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'UserRegistrationExample' do
 use_frameworks!
 pod 'Alamofire', '~> 4.3'
end
  • Now come back to the terminal window and run the following command.
pod install
  • This will install Alamofire to your project. Now just go inside your project folder and open the file ProjectName.xcworkspace.

Creating Interface

  • In Main.storyboard create the following screen.

user registration screen

  • As you can see we have 5 TextFields, a Button and a Label.

Connecting Views with Code

  • Now connect all your views to your ViewController.swift file. I already explained it in previous tutorials. You can go the tutorial from these links.

Xcode Text Field Tutorial for iOS Application using Swift

Xcode Button Tutorial for iPhone using Swift in Xcode 7

Adding User Registration

  • Now just modify the code as below to make the user register to the app.
//
//  ViewController.swift
//  UserRegistrationExample
//
//  Created by Belal Khan on 05/02/17.
//  Copyright © 2017 Belal Khan. All rights reserved.
//

import Alamofire
import UIKit

class ViewController: UIViewController {

    //Defined a constant that holds the URL for our web service
    let URL_USER_REGISTER = "http://192.168.1.105/SimplifiediOS/v1/register.php"
    
    //View variables
    @IBOutlet weak var textFieldUsername: UITextField!
    @IBOutlet weak var textFieldPassword: UITextField!
    @IBOutlet weak var textFieldEmail: UITextField!
    @IBOutlet weak var textFieldName: UITextField!
    @IBOutlet weak var textFieldPhone: UITextField!
    @IBOutlet weak var labelMessage: UILabel!
    
    //Button action
    @IBAction func buttonRegister(_ sender: UIButton) {
        
        //creating parameters for the post request
        let parameters: Parameters=[
            "username":textFieldUsername.text!,
            "password":textFieldPassword.text!,
            "name":textFieldName.text!,
            "email":textFieldEmail.text!,
            "phone":textFieldPhone.text!
        ]
        
        //Sending http post request
        Alamofire.request(URL_USER_REGISTER, method: .post, parameters: parameters).responseJSON
        {
            response in
            //printing response
            print(response)
            
            //getting the json value from the server
            if let result = response.result.value {
                
                //converting it as NSDictionary
                let jsonData = result as! NSDictionary
                
                //displaying the message in label
                self.labelMessage.text = jsonData.value(forKey: "message") as! String?
            }
        }
    
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

Testing the Application

  • Now just launch the application in Simulator.
ios user registration example

iOS Registration Form Example

  • We have the success message. Now lets check the MySQL Database.
iOS Registration Form Example

iOS Registration Form Example

  • Bingo! Its working absolutely fine.

Download Source Code

  • If you are still having troubles you can get the source code from below link.

[sociallocker] iOS Registration Form Example Source Code  [/sociallocker]

So thats all for this iOS Registration Form Example friends. Stay tuned and in the next post we will work on the same project to make the User Login option. And you can leave your comments for queries and feedbacks. Thank You 🙂

Share this:

  • Tweet
  • Share on Tumblr
  • WhatsApp

Related

Filed Under: iOS Development Tutorial Tagged With: how to create a registration form in xcode, ios php, ios registration form example

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, iphone etc.

Comments

  1. Mohamad Habibi says

    February 6, 2017 at 3:10 pm

    Alhamdulillah, Belal Khan, finally there’s an iOS version of your simplifiedcoding.net, just can’t believe it!
    Great job ! And I really mean it, because I find it very difficult to find online resources for learning iOS in easy way, until you come to the rescue 🙂
    I wish you good luck, no matter what, and keep posting useful and easy resources.

    Reply
  2. Eric Park says

    February 9, 2017 at 4:14 pm

    Thanks to Belal Kahn I am learning Xcode easily. However, after follow your instruction, my Xcode Console returns this response.

    “FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)”

    Can someone help me please?

    Reply
    • Mr. Gemu says

      May 26, 2017 at 7:12 am

      abt alamofire it depends on the xcode version

      Reply
  3. Alanoud says

    March 11, 2017 at 12:42 am

    Thank you, can you please do the ios login example.

    Reply
  4. mukta ghosh says

    March 19, 2017 at 9:15 am

    my app build successfully but can’t run.it great threat.

    application UIApplication 0x00007ff42ac00a50
    self myiosapp.AppDelegate 0x000060800002e140

    Reply
  5. khadija haasn says

    March 25, 2017 at 2:02 pm

    I have done the part related to the PHP Storm , but it did not work for me . It does not insert a new record to the database and it always shows not valid request message. What does cause this problem ?

    Reply
  6. sduoanmni ksdhkah says

    April 14, 2017 at 1:34 am

    http not accepted only https is accepted pls help. it is a nsapplicationtraportation error

    Reply
  7. korpo says

    April 15, 2017 at 6:12 pm

    could you please do the login guide as well 🙂

    Reply
  8. Hizkia Nowaly says

    May 14, 2017 at 2:03 pm

    i hv done all the part. i hv tryed using postman too and it works when i add data to mysql. but when i testing to application it didnt works anymore, the data cant be added to mysql. what does cause this problem?

    Reply
    • Mr. Gemu says

      May 26, 2017 at 7:07 am

      I think u jus copast the script, try to drag fieldname and button rename with manually, nothing copast.

      Reply
  9. Mr. Gemu says

    May 26, 2017 at 7:01 am

    Thanks in advance, I need much more time to make it’s work, but finally I can. I am so happy, I hope god bless u

    Reply
  10. Hardik Dabhi says

    July 16, 2017 at 9:00 am

    Does This api work for afnetworking?
    I am using objective c ,so for Api I have used AFnetworking ,but problem is that the registration is done completely but the response is in form of error.

    Reply
  11. Nan says

    August 8, 2017 at 2:10 pm

    thank you Belal for great lesson , i rellay i meant it , i have problem when i’m useing [almofire] the Xcode can’t dealing with this class .

    Reply
    • Nan says

      August 8, 2017 at 4:50 pm

      i’m using Xcode 8
      what i should replace it by?

      Reply
  12. Rasha says

    August 9, 2017 at 7:11 am

    thank u for great Lesson i’m follwing the insteraction then my Xcode Show this for me :

    //converting it as NSDictionary
    let jsonData = result as! NSDictionary
    display ::
    Cast from ‘String’ to unrelated type ‘NSDictionary’ always fails

    what i shoud do ?
    another question if i want to display Alert message not label Like u
    where can i put this code ?

    Reply
  13. Satyajeet says

    November 10, 2017 at 5:30 am

    Hi Belal

    I am trying to execute the code but i am getting an error “{“error”:true,”message”:”Some error occurred”}” . It seems my insert statement is failing, what i could be doing wrong ? When i tried to hard code values into the INSERT statement of DbOperations.php it worked

    Reply
  14. Mason says

    November 14, 2017 at 2:40 pm

    Hey! thank you for such a great tutorial but I’m getting an error whenever I actually go to register (responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength))
    I’ve tried looking this up but couldn’t find a solution.

    Reply
  15. alexus says

    November 29, 2017 at 6:27 am

    can you show the file structure for the actual hosting deployment?

    Reply
  16. Gino says

    December 14, 2017 at 4:12 pm

    I don’t undestand how fix error:

    FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength)

    I use xCode 8 and Swift 3

    Can you help me, please?

    Reply
    • fahad says

      April 6, 2018 at 5:51 pm

      Hi
      how I need cods to do application mobile

      Reply
  17. Daniel says

    January 26, 2018 at 5:20 pm

    Hello, on my DbOperation.php file it says this error everytime I try to run a POST request:

    – Parse error: syntax error, unexpected ‘->’ (T_OBJECT_OPERATOR) in /var/www/html/ComputAS/includes/DbOperation.php on line 20 .

    However, the unexpected -> is used in your code and you code apparently works. Any fix for this ??

    Reply
  18. Kathi says

    March 21, 2018 at 5:23 am

    Gift for yourself buy cheap jerseys online,price favorite and
    easy exchange or refund,come store: nba replica jersey

    Reply

Leave a Reply Cancel reply

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




About Me

belal khan simplified ios

Hello I am Belal Khan, founder and owner of Simplified iOS. I am currently pursuing MCA from St. Xavier's College, Ranchi. Apart from my academic I am a blogger, I run various websites and majority of them are about coding and development.

Connect with Me

Follow Simplified iOS

Simplified iOS

Popular Posts

  • Swift PHP MySQL Tutorial – Connecting iOS App… (94,532)
  • Swift SQLite Tutorial for Beginners – Using… (94,175)
  • UIWebView Example to Load URL in iOS using Swift in Xcode (78,244)
  • Xcode Login Screen Example using Swift 3, PHP and MySQL (65,225)
  • Download Full High Sierra Installer to Create Bootable USB (61,246)
  • How to Format USB on Mac? Formatting External Hard… (60,779)
  • Swift JSON Tutorial – Fetching and Parsing… (58,674)
  • Firebase Realtime Database Tutorial for Swift using Xcode (52,001)
  • iOS Registration Form Example using PHP and MySQL (46,976)
  • Xcode Text Field Tutorial for iOS Application using Swift (39,039)




About

Simplified iOS is a blog where you can find latest tutorials related to coding and app development for iphone and MAC OS. Here you can get Simplified iPhone, iPad and Mac OS development tutorial to know the things about Apple Development from basics to advanced level.

Quick Links

  • Advertise
  • Contact
  • Disclaimer
  • Privacy Policy
  • Write for Us

Copyright © 2017 · Simplified iOS· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·