api de gestion de ticket, basé sur php-crud-api. Le but est de décorrélé les outils de gestion des données, afin
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

core.php 1.9KB

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