我正在尝试使用angularjs将数据从前端插入到mysql数据库中。 但即使没有错误消息,也没有插入数据库。以下是我使用的代码。
的index.html
<html ng-app="demoApp">
<head>
<title> AngularJS Sample</title>
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<div class="container" ng-view>
</div>
</body>
</html>
的script.js
demoApp.config( function ($routeProvider,$locationProvider) {
$routeProvider
.when('/',
{
controller: 'SimpleController',
templateUrl: 'Partials/view1.html'
})
.when('/view2',
{
controller: 'SimpleController',
templateUrl: 'Partials/view2.html'
})
.otherwise({redirectTo: '/'});
});
demoApp.controller('SimpleController',function ($scope,$http){
$http.post('server/view.php').success(function(data){
$scope.friends = data;
});;
$scope.addNewFriend = function(add){
var data = {
fname:$scope.newFriend.fname,
lname:$scope.newFriend.lname
}
$http.post("server/insert.php",data).success(function(data, status, headers, config){
console.log("inserted Successfully");
});
$scope.friends.push(data);
$scope.newFriend = {
fname:"",
lname:""
};
};
});
View1.html
<div class="container" style="margin:0px 100px 0px 500px;">
Name:<input type="text" ng-model="filter.name">
<br/>
<ul>
<li ng-repeat="friend in friends | filter:filter.name | orderBy:'fname'">{{friend.fname}} {{friend.lname}}</li>
</ul>
<br/>
<fieldset style="width:200px;">
<legend>Add Friend</legend>
<form name="addcustomer" method="POST">
First Name:<input type="text" ng-model="newFriend.fname" name="firstname"/>
<br/>
Last Name :<input type="text" ng-model="newFriend.lname" name="lastname"/>
<br/>
<button data-ng-click="addNewFriend()" name="add">Add Friend</button>
</form>
</fieldset>
<a href="#/view2" style="margin:auto;">Next</a>
</div>
以下是我的php文件
insert.php
<?php
if(isset($_POST['add']))
{
$firsname=$_POST['firstname'];
$laname = $_POST['lastname'];
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("angularjs") or die(mysql_error());
mysql_query("INSERT INTO friends (fname,lname) VALUES ('$firsname', '$laname')");
Print "Your information has been successfully added to the database.";
}
?>
我知道我在做一些愚蠢的事情。我今天刚刚开始学习angularjs。 当我尝试使用普通的html插入数据库的PHP代码时,它完美地工作。我没有得到我在这里做错了什么。希望有人能帮到我这里
答案 0 :(得分:17)
您插入数据的脚本错误。将其替换为以下
$http.post("server/insert.php",{'fstname': $scope.newFriend.fname, 'lstname': $scope.newFriend.lname})
.success(function(data, status, headers, config){
console.log("inserted Successfully");
});
并且还按如下方式更改php。
$data = json_decode(file_get_contents("php://input"));
$fstname = mysql_real_escape_string($data->fstname);
$lstname = mysql_real_escape_string($data->lstname);
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("angularjs") or die(mysql_error());
mysql_query("INSERT INTO friends (fname,lname) VALUES ('$fstname', '$lstname')");
Print "Your information has been successfully added to the database.";
当我尝试使用您的代码时,这对我有用。