简体   繁体   中英

Creating new plugin for webservice

I wrote this code to connect to a database, make some queries and send them by json like web api .

I want to create plugin that will work like a WEB API. Then upload it on WP modules on internet and people may install them on their sites to connect my android App. Anywhere.

This is my php code (include db_connect and sending json and respond to my Android App)

<?php
    if(!isset($_REQUEST ['id']))
        echo "id is not set";
    if (isset ( $_REQUEST ['id'] )) {
        $id = $_REQUEST ['id'];
        $response = array ();
        mysql_connect('localhost','db_admin','password') or die(mysql_error());
        mysql_select_db('db_name') or die(mysql_error());
        $sql= "select * from employee";
        $run=mysql_query($sql);
        if (mysql_num_rows ($run) > 0) {
            while ($row=  mysql_fetch_array($run)){
                $product = array ();
                $product ["id"] = $row [0];
                $product ["name"] = $row [1];
                $product ["salary"] = $row [2];
                $response [] = $product;
            }
            echo  json_encode ( $response );
        }
    }
?>

My manager wants me not to use the default Woocommerse WORDPRESS API ,so I have to create new plugin. and want to know how can I convert it to standard module?

Is it possible at all ?

If I was you I will created like this: First off would create handler for the request, either via ajax (im not sure if this way is supported in android ) like this;

function get_some_information(){
    $user_id = $_REQUEST['id'];
    if(!isset($user_id) || empty($user_id)){
       return json_encode([
            'success' => false,
            'message' => 'Empty Request'
       ]);
    }
    $data = get_info_from_data($user_id);
    if(!empty($data)){
        echo json_encode($data);
        exit;

    }else{
        echo json_encode([
            'success' => false,
            'message' => 'Error while processing data'
        ]);
        exit;
    }

}
add_action('wp_ajax_get_some_information', 'get_some_information'); //for auth users
add_action( 'wp_ajax_nopriv_get_some_information', '_get_some_information' ); //for the rest

Note: there is an exit; you always need to terminate the application to be able to get the json, otherwise the output it will be 0 With this now we have an access point to data and validation; and it looks a bit more clean.

function get_some_information($id){
  $result = [];
  // do all things and added to the array

  return $result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM