php 在angularjs中将数据插入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37722797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:21:21  来源:igfitidea点击:

Insert data into database in angularjs

phpangularjs

提问by Rishabh

I am trying to insert data in database but its not working at all! I followed a tutorial and work according to it But its not working. I tried a lot but no success till now.

我正在尝试在数据库中插入数据,但它根本不起作用!我遵循了一个教程并根据它工作但它不起作用。我尝试了很多,但直到现在都没有成功。

Here is my html file

这是我的 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>

And insert.php in which I am inserting data in database

和 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."')");
?>

UPDATE

更新

    <?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);
?>

After Updating my code I got this error :-

更新我的代码后,我收到此错误:-

Notice: Trying to get property of non-object in E:\xampp\htdocs\insert.php on line 4

Notice: Trying to get property of non-object in E:\xampp\htdocs\insert.php on line 5

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

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

I searched regarding this error and found many result but none of them was helpful in my case!

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

回答by Tirthraj Rao

I modified your code in the following manner

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

HTML CODE:

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("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>

and test.php

和 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;
?>

This works well..

这很好用..

回答by Chintan

**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);
?>

回答by jeroen

You are emptying your values(setting them to false...) using mysql_real_escape_string()before you open a database connection. You should open the connection first.

在打开数据库连接之前,您正在清空您的值(将它们设置为false...)mysql_real_escape_string()。您应该先打开连接。

But the best solution would be to switch to PDO or mysqli and use prepared statements. Then you don't have to do any escaping any more.

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

回答by Archish

change your code like this, it might solve your problem.

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

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']);

回答by Hajis Hakkim

you can insert data with image and also validate input.

您可以插入带有图像的数据并验证输入。

<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

插入.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

<?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);
?>