在angularjs中将数据插入数据库

时间:2016-06-09 10:02:30

标签: php angularjs

我正在尝试在数据库中插入数据,但它根本不起作用!我按照教程进行了操作,但它不起作用。我尝试了很多但直到现在都没有成功。

这是我的html文件

<!DOCTYPE html>
<html>
<script  src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">  </script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<form>
Name:-<input type="text" ng-model="bname" />
Phone:-<input type="text" ng-model="bphone" />
<input type="button" value="Submit" ng-click="insertData()" />
</form>
</div>
<script>
 var app = angular.module('myApp',[]);
 app.controller('myCtrl',function($scope,$http){    
 $scope.insertData=function(){      
 $http.post("insert.php", {
    'bname':$scope.bname,
    'bphone':$scope.bphone})        

 .success(function(data,status,headers,config){
 console.log("Data Inserted Successfully");
 });
    }
     });
     </script>

</body>
</html>

我在数据库中插入数据的insert.php

<?php 
$data = json_decode(file_get_contents("php://input"));
$bname = mysql_real_escape_string($data->bname);
$bauthor = mysql_real_escape_string($data->bphone);
mysql_connect("localhost", "root", ""); 
mysql_select_db("angular");
mysql_query("INSERT INTO ang('name', 'phone')    VALUES('".$bname."','".$bauthor."')");
?>

更新

    <?php 
$data = json_decode(file_get_contents("php://input"));
$con = new mysqli('localhost', 'root', '', 'angularjs');
$bname = mysqli_real_escape_string($con, $data->bname);
$bphone = mysqli_real_escape_string($con, $data->bphone);
if($con->connect_errno > 0){
  die('Unable to connect to database [' . $con->connect_error . ']');
}
mysqli_query($con,"INSERT INTO jstable (name, phone)VALUES ('".$bname."', '".$bphone."')");    
mysqli_close($con);
?>

更新我的代码后,我收到了这个错误: -

  

注意:尝试在第4行的E:\ xampp \ htdocs \ insert.php中获取非对象的属性

     

注意:尝试在第5行的E:\ xampp \ htdocs \ insert.php中获取非对象的属性

我搜索了这个错误,发现了很多结果,但没有一个对我的情况有帮助!

5 个答案:

答案 0 :(得分:3)

我以下列方式修改了您的代码

HTML CODE:

<!DOCTYPE html>
<html>
<script  src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">  </script>
<body>
    <div ng-app="myApp" ng-controller="myCtrl">
        <form>
            Name:-<input type="text" ng-model="bname" />
            Phone:-<input type="text" ng-model="bphone" />
            <input type="button" value="Submit" ng-click="insertData()" />
        </form>
    </div>
    <script>
    var app = angular.module('myApp',[]);
    app.controller('myCtrl',function($scope,$http){    
        $scope.insertData=function(){      
            $http.post("test.php", {
                'bname':$scope.bname,
                'bphone':$scope.bphone
            }).then(function(response){
                    console.log("Data Inserted Successfully");
                },function(error){
                    alert("Sorry! Data Couldn't be inserted!");
                    console.error(error);

                });
            }
        });
    </script>

</body>
</html>

和test.php

<?php 
$data = json_decode(file_get_contents("php://input"));
// $bname = mysql_real_escape_string($data->bname);
// $bauthor = mysql_real_escape_string($data->bphone);

$bname = $data->bname;
$bphone = $data->bphone;


mysql_connect("localhost", "root", "password"); 
mysql_select_db("test");

mysql_query("INSERT INTO `ang`(`name`,`phone`)
    VALUES ('".$bname."','".$bphone."') ") or die(mysql_error());
echo $bname." ".$bphone;
?>

效果很好..

答案 1 :(得分:1)

**insert.php**

<!DOCTYPE html>
<html>
<script  src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">  </script>
<body>
    <div ng-app="myApp" ng-controller="myCtrl">
        <form>
            Name:-<input type="text" ng-model="uname" />
            Phone:-<input type="text" ng-model="uphone" />
            <input type="button" value="Submit" ng-click="insertData()" />
        </form>
    </div>
    <script>
    var app = angular.module('myApp',[]);
    app.controller('myCtrl',function($scope,$http){    
        $scope.insertData=function(){      
            $http.post("testinsert.php", {
                'uname':$scope.uname,
                    'uphone': $scope.uphone
                })
                    .success(function (data, status, headers, config) {
                        console.log("Inserted Successfully!");


                    });
            }
        });
    </script>

</body>
</html>

**testinsert.php**

<?php 
$data = json_decode(file_get_contents("php://input"));
$uname = $data->uname;
$uphone = $data->uphone;
$con = mysql_connect("localhost","root","");
mysql_select_db("angular");
$sql = "insert into Table Name(user_name,user_phone) values('$uname','$uphone')";
$result = mysql_query($sql);
?>

答案 2 :(得分:0)

在打开数据库连接之前,您使用false emptying your values(将它们设置为mysql_real_escape_string() ...)。您应该先打开连接。

但最好的解决方案是切换到PDO或mysqli并使用预准备语句。然后你就不必再逃避了。

答案 3 :(得分:0)

像这样更改你的代码,它可能会解决你的问题。

mysql_connect("localhost", "root", ""); 
mysql_select_db("angular");
$data = json_decode(file_get_contents("php://input"),true);
$bname = mysql_real_escape_string($data['bname']);
$bauthor = mysql_real_escape_string($data['bphone']);

答案 4 :(得分:0)

您可以使用图片插入数据并验证输入。

<form ng-controller="insert_Ctrl"  method="post" action=""  name="myForm" enctype="multipart/form-data" novalidate>
    <div>
        <p><input type="text" class="form-control" placeholder="Name" name="name" ng-model="name" required>
            <span style="color:red" ng-show="myForm.name.$invalid&&myForm.name.$touched">Enter Name</span>
        </p>
    </div>
    <div>
        <p><input type="file" ng-model="myFile" class="form-control"  onchange="angular.element(this).scope().uploadedFile(this)">
            <span style="color:red" ng-show="(myForm.myFile.$error.required&&myForm.myFile.$touched)">Select Picture</span>
        </p>
    </div>
    <div>
        <input type="button" name="submit2"  ng-click="uploadFile()" class="btn-primary" ng-disabled="myForm.name.$invalid || myForm.myFile.$invalid" value="Insert">
    </div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
<script src="insert.js"></script>

<强> insert.js

var app = angular.module('myApp',[]);
app.service('uploadFile', ['$http','$window', function ($http,$window) {
    this.uploadFiletoServer = function(file,info,uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        fd.append('data', angular.toJson(info));
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(data){
            alert("insert successfull");
            $window.location.href = ' ';//your window location
        })
        .error(function(){
            alert("Error");
        });
    }
}]);
app.controller('insert_Ctrl',  ['$scope', 'uploadFile', function($scope, uploadFile){
    $scope.uploadFile = function() {
        $scope.myFile = $scope.files[0];
        var file = $scope.myFile;
        var info = {
            'name':$scope.name,
        };
        var url = "save_data.php";
        uploadFile.uploadFiletoServer(file,info,url);
    };
    $scope.uploadedFile = function(element) {
        var reader = new FileReader();
        reader.onload = function(event) {
            $scope.$apply(function($scope) {
                $scope.files = element.files;
                $scope.src = event.target.result  
            });
        }
        reader.readAsDataURL(element.files[0]);
    }
}]);

<强> save_data.php

<?php
    require "dbconnection.php";
    $datas=$_POST['data'];
    $myArray = json_decode($datas, true);
    $name=$myArray['name'];
    $ext = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
    $image = time().'.'.$ext;
    move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$image);
    $query="insert into test_table values ('null','$name','$image')";
    mysqli_query($con,$query);
?>