1

I have an Angular + PHP application and I'm having problem to delete an customer.

I got no error, actually, the application returns sucecess, but it doesn't delete the customer from my database.

This is my angular controller

    app.controller('consultar_cliente_controller', function($scope, $http){
    $scope.listaDeCliente = [];

    var init = function(){
        $scope.buscar();
    };

    $scope.buscar = function(){
        $http.get('consultar_cliente.php')
             .success(function(data){
                $scope.listaDeCliente = data;
             })
             .error(function(){
                console.error('Erro ao executar o GET do cliente');
             });
    };

    $scope.deletar = function(id){
        $http.delete('remover_cliente.php/' + id)
             .success(function(){
                console.log('Cliente removido com sucesso!');
                $scope.buscar();
             })
             .error(function(){
                console.error('Erro ao remover cliente');
             })
    };

    init();
});

This is my PHP

<?php
  $dbh = new PDO('pgsql:host=localhost;dbname=livraria_glp', 'postgres');
  /*
  * Recuperando todos os detalhes da requisição HTTP do Angular
  */ 
  $postdata = file_get_contents("php://input");
  $request  = json_decode($postdata);
  @$id      = $request->id;

  echo $id;

  $dbh->exec("DELETE FROM PRODUTO WHERE ID = '$id'") or die( $dbh->errorInfo() );

?>

And this is my HTML

<div class="well">
  <div class="container">
      <h2>Dados</h2>
      <div class="form-group">
        <label>Nome</label>
          <input class="form-control" type="text" ng-model="filtroNome" />
      </div>
  </div>
  <div class="container resultado">      
    <table class="table">
      <thead>
        <tr>
          <th>Nome</th>
          <th>CPF</th>
          <th>E-mail</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="cliente in listaDeCliente | filter : filtroNome">
          <td>{{cliente.nome}}</td>
          <td>{{cliente.cpf}}</td>
          <td>{{cliente.id}}</td>
          <td><button class="btn btn-danger" ng-click="deletar(cliente.id)">Deletar</button></td>
        </tr>
      </tbody>
    </table>
  </div>
  <button class="btn btn-success" onclick="window.location.href='javascript:window.history.go(-1)'">Voltar</button>
</div>

Edit: I've tried this on PHP:

echo "DELETE FROM PRODUTO WHERE ID = '$id'";

And it returned:

DELETE FROM PRODUTO WHERE ID = ''

Why can't the PHP recieve the id?

3
  • Hello SQL injection vector, good-bye PRODUTO table data Commented Jun 11, 2015 at 1:44
  • Phil, it's just a studdying project. Commented Jun 11, 2015 at 1:50
  • Try debugging $postdata. A proper debugger would be good but at a minimum, try $postdata = file_get_contents('php://input'); var_dump($postdata); exit; Commented Jun 11, 2015 at 2:05

2 Answers 2

2

Angular doesn't send a request body for DELETE so you're going to have to read id from the URL. You might as well just pass it as a query parameter

$http.delete('remover_cliente.php', {
    params: {id: id}
})

Then read it via $_GET['id'].

<?php
if (!isset($_GET['id'])) {
    exit;
}

$id = $_GET['id'];
$dbh = new PDO('pgsql:host=localhost;dbname=livraria_glp', 'postgres');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $dbh->prepare('DELETE FROM PRODUTO WHERE ID = ?');
$stmt->execute([$id]);

echo $id;

Alternatively (and just in case $_GET doesn't work for DELETE requests), you could try forcing the request message data using

$http.delete('remover_cliente.php', {
    data: {id: id}
})

however I don't know if this is supported and it's certainly not very REST-ful. If it does work, you can continue to use file_get_contents('php://input') and json_decode().

Sign up to request clarification or add additional context in comments.

3 Comments

YAY!! Your second solution worked perfectly!! Didn't change my original code, besides the {data: {id: id}}. Thank you!!!
@guuilp please take note of the SQL-injection free PHP code in the first part
Ok Phil. My knowledge about SQL-injection is very poor, but I'll study about it and fix my code. If you recommend any material, I'd be very thankful (again) :D
1

Please try to replace this,

$scope.deletar = function(id){
    var postData = {'id' : id};
    $http.delete('remover_cliente.php', postData)
         .success(function(){
            console.log('Cliente removido com sucesso!');
            $scope.buscar();
         })
         .error(function(){
            console.error('Erro ao remover cliente');
         })
};

5 Comments

I've tried, but doesn't woked :(, my php still can't recieve the id's value
Don't worry man! Unfortunately, still didn't work =(. The statement in PHP still DELETE FROM PRODUTO WHERE ID = ''
@KelvinKyaw OP isn't using any PATH_INFO data so your initial answer should have sufficed.
@Phil yes. But, I can't imagine that why can't get this value from server side.
Kelvin, tried your updated solution with the postData and still didn't work =(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.