Advertisement
Guest User

Untitled

a guest
Jan 18th, 2016
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 KB | None | 0 0
  1. <?php
  2.  
  3. $dbparams = array(
  4. 'host' => 'localhost',
  5. 'user' => '********',
  6. 'password' => '************',
  7. 'dbname' => 'angularjs',
  8. );
  9.  
  10. <?php
  11.  
  12. //nécessite Slim
  13. require 'vendor/autoload.php';
  14. require 'config/config.php';
  15.  
  16. //Instancie une app de Slim
  17. $app = new SlimApp;
  18.  
  19. //Associe type de requête avec fonction et paramêtres
  20. $app->get('/items', 'getItems');
  21. $app->get('/items/{id:d+}', 'getItemById');
  22.  
  23. //Démarre l'application
  24. $app->run();
  25.  
  26. // Accès à la base de données
  27. function DB_Connection() {
  28. $dbhost = $dbparams['host'];
  29. $dbuser = $dbparams['user'];
  30. $dbpass = $dbparams['password'];
  31. $dbname = $dbparams['dbname'];
  32. $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
  33. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  34. return $dbh;
  35. }
  36.  
  37. function getItems() {
  38. $sql = "select * FROM aj_items";
  39. try {
  40. $db = DB_Connection();
  41. $stmt = $db->query($sql);
  42. $list = $stmt->fetchAll(PDO::FETCH_OBJ);
  43. $db = null;
  44. echo json_encode($list);
  45. } catch(PDOException $e) {
  46. echo '{"error":{"text":'. $e->getMessage() .'}}';
  47. }
  48. }
  49.  
  50. function getItemById($req, $resp, $args) {
  51. $id = $args["id"];
  52. $sql = "select * FROM aj_items WHERE id=".$id;
  53. try {
  54. $db = DB_Connection();
  55. $stmt = $db->query($sql);
  56. $list = $stmt->fetchAll(PDO::FETCH_OBJ);
  57. $db = null;
  58. echo json_encode($list);
  59. } catch(PDOException $e) {
  60. echo '{"error":{"text":'. $e->getMessage() .'}}';
  61. }
  62. }
  63.  
  64. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement