2016-02-23 42 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; 
}