madson gr madson gr - 3 months ago 15
AngularJS Question

PHP switch case + PDO Update DB

I am sending data to a php file using AngularJS on ng-click. I have 2 buttons and I am trying to send it to the same php file to insert into the db using switch case but it is not updating the db.

How can I fix my php?

insert.php

<?php

include_once('conn.php');

$data = json_decode(file_get_contents("php://input"));

switch($data){

case 'getvou':
$vou = $data->getvou;
$sql = $mysqli->query("UPDATE audiencia SET vou = '".$vou."'");
$mysqli->close();
break;

case 'getnaovou':
$naovou = $data->getnaovou;
$sql = $mysqli->query("UPDATE audiencia SET nao_vou = '".$naovou."'");
$mysqli->close();
break;
}

?>


script.js

$scope.add_vou = function(){

$scope.vou += 1;

$http.post("http://localhost/insert-audiencia.php", {'getvou': $scope.vou}).then(function(resp){
console.log(JSON.stringify(resp));
console.log(resp);
});
}

$scope.add_nao_vou = function(){

$scope.nao_vou += 1;

$http.post("http://localhost/insert-audiencia.php", {'getnaovou': $scope.nao_vou}).then(function(resp){
console.log(JSON.stringify(resp));
console.log(resp);
});
}

Answer

$data will be a JSON object, which will not equal either of those strings, so no case will be matched in your switch.

With the way you're currently sending the data, you need to be checking instead to see if the JSON object has a property.

if (property_exists($data, 'getvou')) {
    // one query
} elseif (property_exists($data, 'getnaovou')) {
    // other query
}

isset($data->getvou) etc. will also work for this.

Comments