I'm trying to create some sort of subscription for sport event. In this case I've created table with gameId and userId. I'm trying to get logged in user id via localStorage. here is my angular code:
app.controller('customersCtrl', function($scope, $http) {
$http.get("php/contents.php")
.then(function (response) {
$scope.games = response.data.games;
});
/*$scope.subscribe = function(something){
// console.log(something);
console.log(localStorage.getItem('loggedUserInfo'));
};*/
$scope.subscribe = function (gameId,userId){
var data = {
userId: localStorage.getItem('loggedUserInfo'),
gameId: gameId
}
//console.log(data);
$http.post("php/subscribe.php", data).success(function(response){
console.log(response);
}).error(function(error){
console.error(error);
});
};
});
here is my PHP code:
<?php
include("../connection.php");
$data = json_decode(file_get_contents("php://input"));
$userId = $data->userId;
$gameId = $data->gameId;
$q = "INSERT INTO subscription (gameId, playerId) VALUES (:game, :user)";
$query = $db->prepare($q);
$execute = $query->execute(array(
":game" => $gameId,
":user" => $userId
));
echo json_encode($data);
?>
When i console $data I get Object {userId: "↵1", gameId: "2"}, but in database goes only gameId, userId is always = 0.
Will be really thankful for help!
localStorage
only stores strings.
Assuming you are using JSON.stringify()
when you do setItem()
you need to do the reverse to turn it from string to object using JSON.parse()
Try
var data = {
userId: JSON.parse(localStorage.getItem('loggedUserInfo')),
gameId: gameId
}
Note you should also make sure that the key exists in localStorage also before passing to the request
Alternatively in php if you were to do:
$userId= json_decode($data->userId);
You should also see proper db insert however mixing data types when posting seems inconsistent and likely confusing later on doing maintenance