• How to create REST API for Android app using PHP, Slim and MySQL – Day 3/5

    8. Now create another class named DbHandler.php This class is one of the important files in our project which provides necessary functions to perform CRUD operations on the database. Every function is self explanatory by it’s name and comments, I don’t have to have to explain much about them.
    DbHandler.php
    <?php
    /**
     * Class to handle all db operations
     * This class will have CRUD methods for database tables
     *
     * @author Ravi Tamada
     */
    class DbHandler {
        private $conn;
        function __construct() {
            require_once dirname(__FILE__) . './DbConnect.php';
            // opening db connection
            $db = new DbConnect();
            $this->conn = $db->connect();
        }
        /* ------------- `users` table method ------------------ */
        /**
         * Creating new user
         * @param String $name User full name
         * @param String $email User login email id
         * @param String $password User login password
         */
        public function createUser($name, $email, $password) {
            require_once 'PassHash.php';
            $response = array();
            // First check if user already existed in db
            if (!$this->isUserExists($email)) {
                // Generating password hash
                $password_hash = PassHash::hash($password);
                // Generating API key
                $api_key = $this->generateApiKey();
                // insert query
                $stmt = $this->conn->prepare("INSERT INTO users(name, email, password_hash, api_key, status) values(?, ?, ?, ?, 1)");
                $stmt->bind_param("ssss", $name, $email, $password_hash, $api_key);
                $result = $stmt->execute();
                $stmt->close();
                // Check for successful insertion
                if ($result) {
                    // User successfully inserted
                    return USER_CREATED_SUCCESSFULLY;
                } else {
                    // Failed to create user
                    return USER_CREATE_FAILED;
                }
            } else {
                // User with same email already existed in the db
                return USER_ALREADY_EXISTED;
            }
            return $response;
        }
        /**
         * Checking user login
         * @param String $email User login email id
         * @param String $password User login password
         * @return boolean User login status success/fail
         */
        public function checkLogin($email, $password) {
            // fetching user by email
            $stmt = $this->conn->prepare("SELECT password_hash FROM users WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->bind_result($password_hash);
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
                // Found user with the email
                // Now verify the password
                $stmt->fetch();
                $stmt->close();
                if (PassHash::check_password($password_hash, $password)) {
                    // User password is correct
                    return TRUE;
                } else {
                    // user password is incorrect
                    return FALSE;
                }
            } else {
                $stmt->close();
                // user not existed with the email
                return FALSE;
            }
        }
        /**
         * Checking for duplicate user by email address
         * @param String $email email to check in db
         * @return boolean
         */
        private function isUserExists($email) {
            $stmt = $this->conn->prepare("SELECT id from users WHERE email = ?");
            $stmt->bind_param("s", $email);
            $stmt->execute();
            $stmt->store_result();
            $num_rows = $stmt->num_rows;
            $stmt->close();
            return $num_rows > 0;
        }
        /**
         * Fetching user by email
         * @param String $email User email id
         */
        public function getUserByEmail($email) {
            $stmt = $this->conn->prepare("SELECT name, email, api_key, status, created_at FROM users WHERE email = ?");
            $stmt->bind_param("s", $email);
            if ($stmt->execute()) {
                $user = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                return $user;
            } else {
                return NULL;
            }
        }
        /**
         * Fetching user api key
         * @param String $user_id user id primary key in user table
         */
        public function getApiKeyById($user_id) {
            $stmt = $this->conn->prepare("SELECT api_key FROM users WHERE id = ?");
            $stmt->bind_param("i", $user_id);
            if ($stmt->execute()) {
                $api_key = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                return $api_key;
            } else {
                return NULL;
            }
        }
        /**
         * Fetching user id by api key
         * @param String $api_key user api key
         */
        public function getUserId($api_key) {
            $stmt = $this->conn->prepare("SELECT id FROM users WHERE api_key = ?");
            $stmt->bind_param("s", $api_key);
            if ($stmt->execute()) {
                $user_id = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                return $user_id;
            } else {
                return NULL;
            }
        }
        /**
         * Validating user api key
         * If the api key is there in db, it is a valid key
         * @param String $api_key user api key
         * @return boolean
         */
        public function isValidApiKey($api_key) {
            $stmt = $this->conn->prepare("SELECT id from users WHERE api_key = ?");
            $stmt->bind_param("s", $api_key);
            $stmt->execute();
            $stmt->store_result();
            $num_rows = $stmt->num_rows;
            $stmt->close();
            return $num_rows > 0;
        }
        /**
         * Generating random Unique MD5 String for user Api key
         */
        private function generateApiKey() {
            return md5(uniqid(rand(), true));
        }
        /* ------------- `tasks` table method ------------------ */
        /**
         * Creating new task
         * @param String $user_id user id to whom task belongs to
         * @param String $task task text
         */
        public function createTask($user_id, $task) {       
            $stmt = $this->conn->prepare("INSERT INTO tasks(task) VALUES(?)");
            $stmt->bind_param("s", $task);
            $result = $stmt->execute();
            $stmt->close();
            if ($result) {
                // task row created
                // now assign the task to user
                $new_task_id = $this->conn->insert_id;
                $res = $this->createUserTask($user_id, $new_task_id);
                if ($res) {
                    // task created successfully
                    return $new_task_id;
                } else {
                    // task failed to create
                    return NULL;
                }
            } else {
                // task failed to create
                return NULL;
            }
        }
        /**
         * Fetching single task
         * @param String $task_id id of the task
         */
        public function getTask($task_id, $user_id) {
            $stmt = $this->conn->prepare("SELECT t.id, t.task, t.status, t.created_at from tasks t, user_tasks ut WHERE t.id = ? AND ut.task_id = t.id AND ut.user_id = ?");
            $stmt->bind_param("ii", $task_id, $user_id);
            if ($stmt->execute()) {
                $task = $stmt->get_result()->fetch_assoc();
                $stmt->close();
                return $task;
            } else {
                return NULL;
            }
        }
        /**
         * Fetching all user tasks
         * @param String $user_id id of the user
         */
        public function getAllUserTasks($user_id) {
            $stmt = $this->conn->prepare("SELECT t.* FROM tasks t, user_tasks ut WHERE t.id = ut.task_id AND ut.user_id = ?");
            $stmt->bind_param("i", $user_id);
            $stmt->execute();
            $tasks = $stmt->get_result();
            $stmt->close();
            return $tasks;
        }
        /**
         * Updating task
         * @param String $task_id id of the task
         * @param String $task task text
         * @param String $status task status
         */
        public function updateTask($user_id, $task_id, $task, $status) {
            $stmt = $this->conn->prepare("UPDATE tasks t, user_tasks ut set t.task = ?, t.status = ? WHERE t.id = ? AND t.id = ut.task_id AND ut.user_id = ?");
            $stmt->bind_param("siii", $task, $status, $task_id, $user_id);
            $stmt->execute();
            $num_affected_rows = $stmt->affected_rows;
            $stmt->close();
            return $num_affected_rows > 0;
        }
        /**
         * Deleting a task
         * @param String $task_id id of the task to delete
         */
        public function deleteTask($user_id, $task_id) {
            $stmt = $this->conn->prepare("DELETE t FROM tasks t, user_tasks ut WHERE t.id = ? AND ut.task_id = t.id AND ut.user_id = ?");
            $stmt->bind_param("ii", $task_id, $user_id);
            $stmt->execute();
            $num_affected_rows = $stmt->affected_rows;
            $stmt->close();
            return $num_affected_rows > 0;
        }
        /* ------------- `user_tasks` table method ------------------ */
        /**
         * Function to assign a task to user
         * @param String $user_id id of the user
         * @param String $task_id id of the task
         */
        public function createUserTask($user_id, $task_id) {
            $stmt = $this->conn->prepare("INSERT INTO user_tasks(user_id, task_id) values(?, ?)");
            $stmt->bind_param("ii", $user_id, $task_id);
            $result = $stmt->execute();
            $stmt->close();
            return $result;
        }
    }
    ?>

    8.2 Handling the API calls

    Now we have all the required classes for the REST API. Now we can start the code to handle all individual api calls.
    8. Inside v1 folder create a file named index.php and add the following code. Here we are including required libraries and other helper functions.
    verifyRequiredParams() – This function verifies the mandatory parameters in the request.
    validateEmail() – Verifies whether email address is valid one or not.
    echoRespnse() – This function will echo the JSON response with a status code.
    index.php
    <?php
    require_once '../include/DbHandler.php';
    require_once '../include/PassHash.php';
    require '.././libs/Slim/Slim.php';
    \Slim\Slim::registerAutoloader();
    $app = new \Slim\Slim();
    // User id from db - Global Variable
    $user_id = NULL;
    /**
     * Verifying required params posted or not
     */
    function verifyRequiredParams($required_fields) {
        $error = false;
        $error_fields = "";
        $request_params = array();
        $request_params = $_REQUEST;
        // Handling PUT request params
        if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
            $app = \Slim\Slim::getInstance();
            parse_str($app->request()->getBody(), $request_params);
        }
        foreach ($required_fields as $field) {
            if (!isset($request_params[$field]) || strlen(trim($request_params[$field])) <= 0) {
                $error = true;
                $error_fields .= $field . ', ';
            }
        }
        if ($error) {
            // Required field(s) are missing or empty
            // echo error json and stop the app
            $response = array();
            $app = \Slim\Slim::getInstance();
            $response["error"] = true;
            $response["message"] = 'Required field(s) ' . substr($error_fields, 0, -2) . ' is missing or empty';
            echoRespnse(400, $response);
            $app->stop();
        }
    }
    /**
     * Validating email address
     */
    function validateEmail($email) {
        $app = \Slim\Slim::getInstance();
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $response["error"] = true;
            $response["message"] = 'Email address is not valid';
            echoRespnse(400, $response);
            $app->stop();
        }
    }
    /**
     * Echoing json response to client
     * @param String $status_code Http response code
     * @param Int $response Json response
     */
    function echoRespnse($status_code, $response) {
        $app = \Slim\Slim::getInstance();
        // Http response code
        $app->status($status_code);
        // setting response content type to json
        $app->contentType('application/json');
        echo json_encode($response);
    }
    $app->run();
    ?>

  • 0 comments:

    Post a Comment

    FAVOURITE LINE

    To steal ideas from one is plagiarism. To steal from many is Research.

    ADDRESS

    Mumbai , Maharashtra

    EMAIL

    shikha.pathak6@gmail.com
    shikha.the.swt.pari@gmail.com

    Skype

    shikha_pari