I have a AngularJS Function that sends an array to my PHP. But how do I go through this array in PHP and insert each value into MySQL database. SoI have the following $http post:
var data = {
"username": $scope.un,
"courses": $scope.selectedCourses
}
$http({
url: "submitCourses.php",
method: "POST",
data: data
}).success(function(response) {
$scope.courseSubmitResponse = response.resp;
});
And the $scope.selectedCourses looks like ["COEN 10", "MATH 54", "HIST 99"] when sent over. So how could I insert each of these values into my database? Is there a way I can assign a php variable to the array, then do a for loop of that php variable? Your help is greatly appreciated.
I am assuming data transmitted from client side to server side is json.
below is the snippet:
$data = json_decode($data, true);
foreach($data as $element) {
list($subject, $mark) = explode(" ", $element);
// insert using PDO into the database.
}
Access your data using:
$data = json_decode(file_get_contents('php://input'));
$user = $data->username;
$coursesArray = $data->courses;
Then loop over your courses and do what you need
var data = {
"username": $scope.un,
"courses": $scope.selectedCourses
}
$http({
url: "submitCourses.php",
method: "POST",
data: data
}).success(function(response) {
$scope.courseSubmitResponse = response[0].resp;
});
Try this code only if response array length is one and if you got multiple records in response you need to get value dynamically might for loop is been usefull