Advertisement
rojolele94

Untitled

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