Browse Source

Added core.php, which shows how the core of the application works

Maurits van der Schee 9 years ago
parent
commit
8fec324e3d
1 changed files with 65 additions and 0 deletions
  1. 65
    0
      core.php

+ 65
- 0
core.php View File

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

Loading…
Cancel
Save