Przeglądaj źródła

updated for PHP7 tests

Maurits van der Schee 7 lat temu
rodzic
commit
e6b92de0c6
1 zmienionych plików z 24 dodań i 22 usunięć
  1. 24
    22
      extras/core.php

+ 24
- 22
extras/core.php Wyświetl plik

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

Loading…
Anuluj
Zapisz