Advertisement
aquilesburlamaqui

apiphpjson

Mar 7th, 2019
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.08 KB | None | 0 0
  1. <?php
  2. error_reporting(~E_WARNING & ~E_NOTICE);
  3.  
  4.   $servername = "localhost";
  5.   $username = "id8850089_db_iot";
  6.   $password = "q1w2e3r4t5y6";
  7.   $dbname = "id8850089_db_iot";
  8.  
  9. // get the HTTP method, path and body of the request
  10. $method = $_SERVER['REQUEST_METHOD'];
  11. $request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
  12. $input = json_decode(file_get_contents('php://input'),true);
  13.  
  14. // connect to the mysql database
  15. $link = mysqli_connect($servername, $username, $password, $dbname);
  16. mysqli_set_charset($link,'utf8');
  17.  
  18. // retrieve the table and key from the path
  19. $table = preg_replace('/[^a-z0-9_]+/i','',array_shift($request));
  20. $key = array_shift($request)+0;
  21.  
  22. // escape the columns and values from the input object
  23. $columns = preg_replace('/[^a-z0-9_]+/i','',array_keys($input));
  24. $values = array_map(function ($value) use ($link) {
  25.   if ($value===null) return null;
  26.   return mysqli_real_escape_string($link,(string)$value);
  27. },array_values($input));
  28.  
  29. // build the SET part of the SQL command
  30. $set = '';
  31. for ($i=0;$i<count($columns);$i++) {
  32.   $set.=($i>0?',':'').'`'.$columns[$i].'`=';
  33.   $set.=($values[$i]===null?'NULL':'"'.$values[$i].'"');
  34. }
  35.  
  36. // create SQL based on HTTP method
  37. switch ($method) {
  38.   case 'GET':
  39.     $sql = "select * from `$table`".($key?" WHERE id=$key":''); break;
  40.   case 'PUT':
  41.     $sql = "update `$table` set $set where id=$key"; break;
  42.   case 'POST':
  43.     $sql = "insert into `$table` set $set"; break;
  44.   case 'DELETE':
  45.     $sql = "delete `$table` where id=$key"; break;
  46. }
  47.  
  48. // excecute SQL statement
  49. $result = mysqli_query($link,$sql);
  50.  
  51. // die if SQL statement failed
  52. if (!$result) {
  53.   http_response_code(404);
  54.   die(mysqli_error());
  55. }
  56.  
  57. // print results, insert id or affected row count
  58. if ($method == 'GET') {
  59.   if (!$key) echo '[';
  60.   for ($i=0;$i<mysqli_num_rows($result);$i++) {
  61.     echo ($i>0?',':'').json_encode(mysqli_fetch_object($result));
  62.   }
  63.   if (!$key) echo ']';
  64. } elseif ($method == 'POST') {
  65.   echo mysqli_insert_id($link);
  66. } else {
  67.   echo mysqli_affected_rows($link);
  68. }
  69.  
  70. // close mysql connection
  71. mysqli_close($link);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement