我是Angular JS的新手,我想将数据从表单插入到MySQL数据库表中(在我的情况下表名是employee)但是当我点击提交时它不插入。我在浏览器中编译了insert.php文件,这给了我这个错误 "试图获取非对象" 的属性。我正在以JSON格式发送数据,然后我在index.php
文件中进行了解码,但当我尝试通过$data
对象访问解码数据时,它给出了我提到的错误。
myApp.js代码
var app = angular.module('myApp',[])
.controller("myController",function($scope,$http){
$scope.insertData = function(){
$http.post("insert.php",{'name': $scope.name,'fname': $scope.fname,'dept': $scope.dept})
.success(function(data,status,headers,config){
console.log("Inserted Successfuly!");
});
}
});
insert.php code
<?php
$data = json_decode(file_get_contents("php://input"));
$name = $data->name;
$fname = $data->fname;
$dept = $data->dept;
$host = 'localhost';
$dbname = 'company';
$dbusername = 'root';
$dbpass = '';
$connection = mysqli_connect($host,$dbusername,$dbpass,$dbname);
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
$query = "INSERT INTO employe ('id','ename','fname','dept') VALUES('','$name','$fname','$dept')";
$query_run = mysqli_query($connection,$query);
}
?>
index.html代码
<html ng-app="myApp">
<head>
<title> Using Angular with PHP! </title>
<!--<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.1/angular.min.js"></script>-->
<style type="text/css" src="css/bootstrap.min.css"></style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12" ng-controller="myController">
<form>
Your Name: <input type="text" ng-model="name" /><br><br>
Father Name: <input type="text" ng-model="fname" /><br><br>
Department : <input type="text" ng-model="dept" /><br><br>
<input class="btn btn-success" type="button" value="Submit" ng-click="insertData()" />
</form>
</div>
</div>
</div>
<script type="text/javascript" src="js/angular/angular.min.js"></script>
<script type="text/javascript" src="js/bootstrap/bootstrap.min.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
</html>
答案 0 :(得分:1)
你会笑,但只要添加这些``围绕你的表名就可以了。
$query = "INSERT INTO `employe`(`id`, `ename`, `fname`, `dept`) VALUES('','$name','$fname','$dept')";