Search code examples
phpmysqlangularjsionic-frameworkangularjs-service

How can use AngularJs $stateChangeSuccess to populate data to MySQL using PHP?


I have this funcion who list objects with arrays:

//onload event-- to set the values
$scope.$on('$stateChangeSuccess', function () {

    $scope.cart=sharedCartService.cart;
    $scope.total_qty=sharedCartService.total_qty;
    $scope.total_amount=sharedCartService.total_amount;     
});    

I need get all datas and insert all (populate) in a database. I´m using MySQL and PHP.

Thanks.


Solution

  • You create a file let say its called save.php

    In that file you will have something like

    header("Access-Control-Allow-Origin: *");
    Global $db;
    $db = new PDO('mysql:dbname=databasename;host=localhost', 'dbuser', 'dbpassword');
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }
    
    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    
        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
        exit(0);
    }
    $postdata = file_get_contents("php://input");
    if (isset($postdata)) {
        $request = json_decode($postdata);
        $cart = $request->cart;
        $total_qty = $request->total_qty;
        $total_amount = $request->total_amount;
    
    }
    else {
        echo "Not called properly!";
    }
    $query = $db->prepare("
                    INSERT INTO yourtable
                        (cart, total_qty, total_amount)
                    VALUES
                        (:cart, :total_qty, :total_amount)");
    
    $query->execute(array(
                    ':cart' => $cart,
                    ':total_qty' => $total_qty,
                    ':total_amount' => $total_amount));
    

    And in your function in Angular (stateChangeSuccess) you make a post request on for example http://localhost:8080/save.php

    $http.post(url, data, config)
    .then(
       function(response){
         // success callback
       }, 
       function(response){
         // failure callback
       }
     );