在角度js中获取php的数组数据并且无法在php中更新数据

时间:2022-04-30 21:33:51

在角度js中获取php的数组数据并且无法在php中更新数据I am new to angular js and i want to update the data of registration form in which i am not able to update data and also how to print array values of php in script file of angular js.Please look forward above the code and give required solutions.

我是角度js的新手,我想更新注册表单的数据,其中我无法更新数据,以及如何在角度js的脚本文件中打印php的数组值。请在代码上方向前看,并提供必要的解决方案。

fetchdata.php:

fetchdata.php:

<?php
    include_once('db.php');
    if(isset($_GET['action'])){
        if($_GET['action']=='add_data'){
          add_data();
        }
        else if($_GET['action']=='get_data'){
          get_data();
        }
        else if($_GET['action']=='delete_data'){
            delete_data();
        }
        else if($_GET['action']=='edit_data'){
            edit_data();
        }
        else if($_GET['action']=='update_data'){
            update_data();
        }
    }

    /*Insert Data*/
    function add_data(){    
        $data = json_decode(file_get_contents("php://input"));
        //print_r($data);
        $fname  = $data->fname;
        $lname  = $data->lname;
        $gender = $data->gender;
        $state  = $data->state;
        $query="INSERT INTO registration 
        (reg_fname, reg_lname, reg_gender, reg_state, reg_id)
         values ('".$fname."', '".$lname."', '".$gender."', '".$state."', NULL)";
        $result = mysql_query($query);
        //echo $query;
        if ($result) {
        $arr = array('msg' => "Data Added Successfully!!!", 'error' => '');
        $jsn = json_encode($arr);
        //print_r($jsn);
        } 
        else{
            $arr = array('msg' => "", 'error' => 'Error in inserting records');
            $jsn = json_encode($arr);
            // print_r($jsn);
        }
    }

    /*View dATA*/
    function get_data(){
        $query=mysql_query("SELECT * FROM registration");
        $data = array();
        while($row=mysql_fetch_array($query)){
            $data[] = array(
                "userid" =>   $row['reg_id'],
                "fname"  =>   $row['reg_fname'],
                "lname"  =>   $row['reg_lname'],
                "gender" =>   $row['reg_gender'],
                "state"  =>   $row['reg_state'],
             );
        }
           //print_r($row);
            print_r(json_encode($data));
            return json_encode($data);
    }

    /*dELETE dATA*/
    function delete_data(){
        $data = json_decode(file_get_contents("php://input")); 
        $index = $data->userid; 
        //print_r($data) ;
        $del = mysql_query("DELETE FROM registration WHERE reg_id = ".$index);
        if($del)
        return true;
        return false; 
    }

    /*Edit Data*/
    function edit_data(){
        $data  = json_decode(file_get_contents("php://input"));
        $index = $data->userid;         
        $qry   = mysql_query("SELECT * FROM registration WHERE reg_id = ".$index);
        $data = array();
        while($row=mysql_fetch_array($qry)){
            $data[]=array(
            "userid" =>$row['reg_id'],
            "fname"  =>$row['reg_fname'],
            "lname"  =>$row['reg_lname'],
            "gender" =>$row['reg_gender'],
            "state"  =>$row['reg_state']
            );
        }
        print_r(json_encode($data));
        return json_encode($data);
    }

    /*update Data*/
    function update_data(){
        $data=json_decode(file_get_contents("php://input"));
        $index  = $data->userid;
        $fname  = $data->fname;
        $lname  = $data->lname;
        $gender = $data->gender;
        $state  = $data->state;
        $query=mysql_query("Update registration SET
                reg_fname='".$fname."',reg_lname='".$lname."',
                reg_gender='".$gender."',reg_state='".$state."' 
                where reg_id=".$index);
        if ($query){
            $arr = array('msg' => "Product Updated Successfully!!!", 'error' => '');
            $jsn = json_encode($arr);
            // print_r($jsn);
        } else {
            $arr = array('msg' => "", 'error' => 'Error In Updating record');
            $jsn = json_encode($arr);
            // print_r($jsn);
        }
    }   
?>

controller.js:

controller.js:

var regform = angular.module('regform',[]);
regform.controller('formController',function($scope,$http){
    $scope.submit=true;
    $scope.reset=true;
    $scope.states = [
        {id:1,name:'Gujarat'},
        {id:2,name:'Haryana'},
        {id:3,name:'MP'},
    ];

    $scope.get_data = function(){
        $http.get('fetchdata.php?action=get_data').success(function(data){
            $scope.fields = data
            return $scope;
        });
    }

    $scope.Save = function(){
        $http.post('fetchdata.php?action=add_data',
            {
                'userid': $scope.userid,
                'fname' : $scope.fname,
                'lname' : $scope.lname,
                'gender': $scope.gender,
                'state' : $scope.selectedState,
            }
        )
        .success(function (data, status, headers, config){
            //alert(JSON.stringify(data));
            //console.log("Data added successfully");
            $scope.get_data();
            //alert("Data added Successfully");
       });
    }

    $scope.delete_id = function(index){
       $http.post('fetchdata.php?action=delete_data',{
                'userid' : index
        })
        .success(function (data, status, headers, config) { 
            $scope.get_data();
        })
    }

    /* Edit data*/
   $scope.edit_id = function(index){
        $scope.update=true;
        $scope.cancel=true;
        $scope.submit=false;
        $scope.reset=false;

        $http.post('fetchdata.php?action=edit_data', {
            'userid' : index
        }) 
        .success(function (data, status, headers, config) { 
            //alert(data[0]["userid"]);
            //alert(JSON.stringify(data));
            $scope.userid = data[0]["userid"];
            $scope.fname  = data[0]["fname"];
            $scope.lname  = data[0]["lname"];
            $scope.gender = data[0]["gender"];
            $scope.selectedState  = parseInt(data[0]["state"]); 
        })
        .error(function(data, status, headers, config){

        });
    }

    $scope.Update = function(){
        $http.post('db.php?action=update_data', {
            'userid' : $scope.userid,
            'fname'  : $scope.fname, 
            'lname'  : $scope.lname, 
            'gender' : $scope.gender,
            'state'  : $scope.selectedState
        })
        .success(function (data, status, headers, config) {
                //alert(JSON.stringify(data));
                $scope.get_data();
                return $scope;
        })
        .error(function(data, status, headers, config){

        });
    }
});

form.html

form.html

<html ng-app="regform">
    <head>
        <title>Registration Form</title>
        <script src="angular.min.js"></script>
        <script src="controller.js">
            /*var regform = angular.module('regform',[]);
            regform.controller('formController',function($scope){
                $scope.states = [
                        {id:1,name:'Gujarat'},
                        {id:2,name:'Haryana'},
                        {id:3,name:'MP'},
                        ];

                $scope.formfields =[];
                $scope.Save = function(form){
                  $scope.formfields.push({fname: $scope.fname,lname: $scope.lname,gender: $scope.gender, state:$scope.state});  
                }


            });*/
        </script>
    </head>
    <body ng-controller="formController">
        <form name="userForm">
        <table>
            <tr>
                <td>
                    FirstName:
                </td>
                <td>
                    <input type="hidden" ng-model="userid" name="userid">
                    <input ng-model="fname" type="text" required ng-minlength="4">
                    <span ng-show="userForm.fname.$error.required">
                         This is a required field
                    </span>
                </td>
            </tr>
            <tr>
                <td>
                    LastName:
                </td>
                <td>
                    <input ng-model="lname" type="text">
                </td>
            </tr>
            <tr>
                <td>
                    Gender:
                </td>
                <td>
                    <input type="radio" ng-model="gender" value="male"   id="male" checked="checked">Male
                    <input type="radio" ng-model="gender" value="female" id="female">Female
                </td>
            </tr>
            <tr>
                <td>
                    State:
                </td>
                <td>
                <select id="stateform" ng-model="selectedState" ng-options="state.id as state.name for state in states">
                     <option value="">- - Make Selection - -</option>
                </select>
                </td>
            </tr>
            <tr>
                <td>
                    <input name="check" id="check" type="checkbox" ng-model="accept" required />Accept
                </td>
            </tr>
            <tr>
                <td>
                     <button ng-show="submit" ng-click="Save()">Save</button>
                     <button ng-show="update" ng-click="Update()">Update</button>
                </td>
                <td>
                     <button ng-show="reset" ng-click="Reset()" type="reset">Reset</button>
                     <button ng-show="cancel" ng-click="clear()">Cancel</button>
                </td>
            </tr>
        </table>
            <br>
            <br>
            <table border="1">
                <thead>
                   <th>UserId</th>
                   <th>FirstName</th>
                   <th>LastName</th>
                   <th>Gender</th>
                   <th>State</th>
                   <th>Action</th>
                </thead>
                <tbody ng-init="get_data()">
                    <tr ng-repeat="field in fields">
                    <td>{{field.userid }}</td>
                    <td>{{field.fname | uppercase}}</td>
                    <td>{{field.lname}}</td>
                    <td>{{field.gender}}</td>
                    <td>{{field.state}}</td>
                    <td><a id="edit" href="" ng-click="edit_id(field.userid)">Edit</a>
                    |&nbsp;<a id="delete" href="" ng-click="delete_id(field.userid)" ng-confirm="Are you sure?">Delete</a></td>
                    </tr>
                </tbody>
            </table>
        </form>
    </body>
</html>

1 个解决方案

#1


0  

Please have look at below changes where i tried to address your issues.

请查看以下我尝试解决您问题的更改。

1) Using below HTML code to list state value

1)使用下面的HTML代码列出状态值

<select id="stateform" ng-model="selectedState" ng-options="state.id as state.name for state in states"> </select>

Here i am using ng-model selectedState which will be set to 0 (make a selection) by default using $scope.selectedState = 0; in angularJS function.

这里我使用的是ng-model selectedState,默认情况下使用$ scope.selectedState = 0设置为0(进行选择);在angularJS函数中。

2) To show data on load and after insert/update , return $scope like below

2)要显示有关加载和插入/更新后的数据,请返回$ scope,如下所示

 $scope.get_data = function(){
    $http.get('update-data.php?action=get_data').success(function(data){

        $scope.fields = data;
        return $scope;
    });
}

3) Wherever you are using $scope.state.name , use $scope.selectedState as i change ng-model.

3)无论您使用$ scope.state.name,使用$ scope.selectedState作为更改ng-model。

Below is complete AngularJS code

下面是完整的AngularJS代码

var regform = angular.module('regform',[]);
regform.controller('formController',function($scope,$http){
$scope.submit=true;
$scope.reset=true;
$scope.selectedState = 0;
$scope.states = [
        {id:0,name:'Make selection'},
        {id:1,name:'Gujarat'},
        {id:2,name:'Haryana'},
        {id:3,name:'MP'},
        ];

$scope.get_data = function(){
    $http.get('update-data.php?action=get_data').success(function(data){

        $scope.fields = data;
        return $scope;
    });
}

$scope.Save = function(){
    $http.post('update-data.php?action=add_data',
        {
            'userid': $scope.userid,
            'fname' : $scope.fname,
            'lname' : $scope.lname,
            'gender': $scope.gender,
            'state' : $scope.selectedState,
        }
    )
    .success(function (){
        $scope.get_data();
        alert('Data updated!!!');
     });
}

$scope.delete_id = function(index){
    $http.post('update-data.php?action=delete_data',{
            'userid' : index
        }
        )
    .success(function () { 
        $scope.get_data();
    })
}
/* Edit data*/
$scope.edit_id = function(index){
    $scope.update=true;
    $scope.cancel=true;
    $scope.submit=false;
    $scope.reset=false;

    $http.post('update-data.php?action=edit_data', {
        'userid' : index
    }) 
    .success(function (data, status, headers, config) { 
        //console.log(data);
        //alert(JSON.stringify(data));
        $scope.userid = data[0]["userid"];
        $scope.fname  = data[0]["fname"];
        $scope.lname  = data[0]["lname"];
        $scope.gender = data[0]["gender"];
        $scope.selectedState  = parseInt(data[0]["state"]); 
    })
    .error(function(data, status, headers, config){

    });
}
$scope.Update = function(){
    $http.post('update-data.php?action=update_data', 
        {
            'userid' : $scope.userid,
            'fname'  : $scope.fname, 
            'lname'  : $scope.lname, 
            'gender' : $scope.gender,
            'state'  : $scope.selectedState
        }
    )
    .success(function () {
            $scope.get_data();
            alert('Data updated!!!');
    })
    .error(function(data, status, headers, config){

    });
}
});

Now reg_state stores numeric value representing state and state name and use mysqli or PDO instead mysql as it is depricated.

现在,reg_state存储表示状态和状态名称的数值,并使用mysqli或PDO代替mysql,因为它已被删除。

Hope this helps you.

希望这对你有所帮助。

#1


0  

Please have look at below changes where i tried to address your issues.

请查看以下我尝试解决您问题的更改。

1) Using below HTML code to list state value

1)使用下面的HTML代码列出状态值

<select id="stateform" ng-model="selectedState" ng-options="state.id as state.name for state in states"> </select>

Here i am using ng-model selectedState which will be set to 0 (make a selection) by default using $scope.selectedState = 0; in angularJS function.

这里我使用的是ng-model selectedState,默认情况下使用$ scope.selectedState = 0设置为0(进行选择);在angularJS函数中。

2) To show data on load and after insert/update , return $scope like below

2)要显示有关加载和插入/更新后的数据,请返回$ scope,如下所示

 $scope.get_data = function(){
    $http.get('update-data.php?action=get_data').success(function(data){

        $scope.fields = data;
        return $scope;
    });
}

3) Wherever you are using $scope.state.name , use $scope.selectedState as i change ng-model.

3)无论您使用$ scope.state.name,使用$ scope.selectedState作为更改ng-model。

Below is complete AngularJS code

下面是完整的AngularJS代码

var regform = angular.module('regform',[]);
regform.controller('formController',function($scope,$http){
$scope.submit=true;
$scope.reset=true;
$scope.selectedState = 0;
$scope.states = [
        {id:0,name:'Make selection'},
        {id:1,name:'Gujarat'},
        {id:2,name:'Haryana'},
        {id:3,name:'MP'},
        ];

$scope.get_data = function(){
    $http.get('update-data.php?action=get_data').success(function(data){

        $scope.fields = data;
        return $scope;
    });
}

$scope.Save = function(){
    $http.post('update-data.php?action=add_data',
        {
            'userid': $scope.userid,
            'fname' : $scope.fname,
            'lname' : $scope.lname,
            'gender': $scope.gender,
            'state' : $scope.selectedState,
        }
    )
    .success(function (){
        $scope.get_data();
        alert('Data updated!!!');
     });
}

$scope.delete_id = function(index){
    $http.post('update-data.php?action=delete_data',{
            'userid' : index
        }
        )
    .success(function () { 
        $scope.get_data();
    })
}
/* Edit data*/
$scope.edit_id = function(index){
    $scope.update=true;
    $scope.cancel=true;
    $scope.submit=false;
    $scope.reset=false;

    $http.post('update-data.php?action=edit_data', {
        'userid' : index
    }) 
    .success(function (data, status, headers, config) { 
        //console.log(data);
        //alert(JSON.stringify(data));
        $scope.userid = data[0]["userid"];
        $scope.fname  = data[0]["fname"];
        $scope.lname  = data[0]["lname"];
        $scope.gender = data[0]["gender"];
        $scope.selectedState  = parseInt(data[0]["state"]); 
    })
    .error(function(data, status, headers, config){

    });
}
$scope.Update = function(){
    $http.post('update-data.php?action=update_data', 
        {
            'userid' : $scope.userid,
            'fname'  : $scope.fname, 
            'lname'  : $scope.lname, 
            'gender' : $scope.gender,
            'state'  : $scope.selectedState
        }
    )
    .success(function () {
            $scope.get_data();
            alert('Data updated!!!');
    })
    .error(function(data, status, headers, config){

    });
}
});

Now reg_state stores numeric value representing state and state name and use mysqli or PDO instead mysql as it is depricated.

现在,reg_state存储表示状态和状态名称的数值,并使用mysqli或PDO代替mysql,因为它已被删除。

Hope this helps you.

希望这对你有所帮助。