Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- header('Access-Control-Allow-Origin:*');
- header('Access-Control-Allow-Headers: X-Requested-With');
- header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
- header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
- //Cargamos el framework
- require_once 'vendor/autoload.php';
- $app = new \Slim\App();
- function getConnection() {
- $dbhost="localhost";
- $dbuser="root";
- $dbpass="";
- $dbname="TestM6";
- $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
- $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- return $dbh;
- }
- $app->get('/productos', function () {
- $sql = "SELECT * FROM Productos";
- try {
- $stmt = getConnection()->query($sql);
- $prod = $stmt->fetchAll(PDO::FETCH_OBJ);
- return json_encode($prod);
- }
- catch(PDOException $e) {
- echo '{"data":{"error":'. $e->getMessage() .'}}';
- }
- });
- $app->get('/productos/{id}', function ($request) {
- $id = $request->getAttribute('id');
- $sql = "SELECT * FROM Productos where id_producto = $id";
- try {
- $stmt = getConnection()->query($sql);
- $producto = $stmt->fetch(PDO::FETCH_ASSOC);
- return json_encode($producto);
- }
- catch(PDOException $e) {
- echo '{"data":{"error":'. $e->getMessage() .'}}';
- }
- });
- $app->delete('/productos/{id}', function ($request) {
- $id = $request->getAttribute('id');
- $sql = "DELETE FROM Productos where id_producto = :id";
- $select = "SELECT * FROM Productos where id_producto = $id";
- try {
- $stmt = getConnection()->query($select);
- $producto = $stmt->fetch(PDO::FETCH_ASSOC);
- $query = getConnection()->prepare($sql);
- $query->bindParam(":id", $id);
- $query->execute();
- return json_encode($producto);
- }
- catch(PDOException $e) {
- echo '{"data":{"error":'. $e->getMessage() .'}}';
- }
- });
- $app->run();
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement