2016-02-23 39 views
1

我編寫了這段代碼來連接數據庫,進行一些查詢並通過json發送,如web api爲webservice創建新插件

我想創建一個像WEB API一樣工作的插件。然後在互聯網上的WP模塊上載它,並且人們可以將它們安裝在他們的網站上以連接我的android應用程序。無處不在。

這是我php代碼(包括db_connect和發送JSON和迴應我的Android應用程序)

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

我的經理要我不要用默認的Woocommerse WORDPRESS API,所以我要創建新的插件。並想知道如何將其轉換爲標準模塊?

有沒有可能?

回答

0

如果我是你,我會創建這樣的: 首先會爲請求創建處理程序,無論是通過AJAX(IM不知道如果在Android是支持這種方式)像這樣;

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 

注:有一個exit;你總是需要終止應用程序能夠得到JSON,否則輸出將是0 有了這個,現在我們有一個接入點的數據和驗證;它看起來更乾淨一點。

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

    return $result; 
}