Advertisement
Guest User

Untitled

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