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.8KB

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