Advertisement
ferrynurr

PHP REST SERVER [GET_METHOD]

Oct 14th, 2018
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.21 KB | None | 0 0
  1. <?php
  2.  
  3. $method = $_SERVER['REQUEST_METHOD'];
  4. $request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
  5. $input = json_decode(file_get_contents('php://input'),true);
  6.  
  7. // konektor mysql
  8. $link = mysqli_connect('localhost', 'root', '', 'iot_bawang');
  9. mysqli_set_charset($link,'utf8');
  10.  
  11. // database set
  12. $nama_tabel = "tanah_lembab";
  13. $field_tb = "id_lembab";
  14. $order = "tgl_update";
  15.  
  16. $data = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
  17. $id = array_shift($request)+0;
  18. if (strcmp($data, 'data') ==0) {
  19.      switch ($method)
  20.      {
  21.          case 'GET':
  22.          $sql = "select * from ".$nama_tabel.($id?" WHERE ".$field_tb."=$id":'')." order by ". $order. " DESC LIMIT 1"; break;
  23.      }
  24.     $result = mysqli_query($link,$sql);
  25.  
  26.      if (!$result) {
  27.      http_response_code(404);
  28.      die(mysqli_error());
  29.      }
  30.  
  31.      if ($method == 'GET') {
  32.      $hasil=array();
  33.      while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
  34.      {
  35.      $hasil[]=$row;
  36.      }
  37.                      
  38.      echo json_encode($hasil);
  39.      
  40.      } elseif ($method == 'POST') {
  41.      echo mysqli_insert_id($link);
  42.      } else {
  43.      echo mysqli_affected_rows($link);
  44.      }
  45. }else{
  46.  $hasil1 = array('status' => false, 'message' => 'Access Denied');
  47.  echo json_encode($hasil1);
  48. }
  49. mysqli_close($link);
  50. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement