Advertisement
Guest User

Untitled

a guest
Apr 8th, 2019
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.18 KB | None | 0 0
  1. <?php
  2.     header('Access-Control-Allow-Origin:*');
  3.     header('Access-Control-Allow-Headers: X-Requested-With');
  4.     header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
  5.     header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
  6.     //Cargamos el framework
  7.  
  8.     require_once 'vendor/autoload.php';
  9.     $app = new \Slim\App();
  10.  
  11.     function getConnection() {
  12.         $dbhost="localhost";
  13.         $dbuser="root";
  14.         $dbpass="";
  15.         $dbname="TestM6";
  16.         $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
  17.         $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  18.         return $dbh;
  19.     }
  20.  
  21.     $app->get('/productos', function () {
  22.         $sql = "SELECT * FROM Productos";
  23.         try {
  24.             $stmt = getConnection()->query($sql);
  25.             $prod = $stmt->fetchAll(PDO::FETCH_OBJ);
  26.             return json_encode($prod);
  27.         }
  28.         catch(PDOException $e) {
  29.             echo '{"data":{"error":'. $e->getMessage() .'}}';
  30.         }
  31.     });
  32.  
  33.     $app->get('/productos/{id}', function ($request) {
  34.         $id = $request->getAttribute('id');
  35.         $sql = "SELECT * FROM Productos where id_producto = $id";
  36.         try {
  37.             $stmt = getConnection()->query($sql);
  38.             $producto = $stmt->fetch(PDO::FETCH_ASSOC);
  39.             return json_encode($producto);
  40.         }
  41.         catch(PDOException $e) {
  42.             echo '{"data":{"error":'. $e->getMessage() .'}}';
  43.         }
  44.     });
  45.  
  46.     $app->delete('/productos/{id}', function ($request) {
  47.         $id = $request->getAttribute('id');
  48.         $sql = "DELETE FROM Productos where id_producto = :id";
  49.         $select = "SELECT * FROM Productos where id_producto = $id";
  50.         try {
  51.             $stmt = getConnection()->query($select);
  52.             $producto = $stmt->fetch(PDO::FETCH_ASSOC);
  53.             $query = getConnection()->prepare($sql);
  54.             $query->bindParam(":id", $id);
  55.             $query->execute();
  56.             return json_encode($producto);
  57.         }
  58.         catch(PDOException $e) {
  59.             echo '{"data":{"error":'. $e->getMessage() .'}}';
  60.         }
  61.     });
  62.  
  63.     $app->run();
  64. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement