它已经两天了,因为我开始学习角js。其实很有趣。我仍然在使用静态数据。结合角js和php - 失败的插入数据到数据库
当你不能操纵数据库仪式时,它意味着什么? 所以我跳进下一步。连接它与我的分贝。即时通讯使用普通的PHP 如果成功,我会跳到下一步,结合像laravel或codeigniter这样的角度和php框架。
其实,它很容易从数据库中检索数据。
但是,即时在这里不要分享这个故事,当我试图将它输入到数据库时,我发现困难。我不明白为什么。重点是我不能从HTML中的形式获取数据。即时通讯工厂使用角度。
这里是我的add.html:
<h1>add newdata</h1>
new name :
<input type='text' ng-model='newdata.name'> <br>
new city :
<input type='text' ng-model='newdata.city'> <br>
<button ng-click='addData()'>submit</button>
这里是我的index.html:
//define dependency ngRoute module
var test = angular.module('testPeople', ['ngRoute']);
test.factory('factoryPeople', function($http) {
var factoryPeople= {};
factoryPeople.getPeople = function() {
return $http.get('data.php');
};
factoryPeople.addPeople = function() {
return $http.post('add.php');
};
return factoryPeople;
});
路线:
test.config(function($routeProvider) {
$routeProvider
.when('/add', {
templateUrl : 'add.html',
controller : 'add'
})
.when('/contact', {
templateUrl : 'contact.html'
})
.when('/second', {
templateUrl : 'index2.html'
})
.otherwise({redirectTo: '/'});
});
控制器:
test.controller('add', function($scope, $http, factoryPeople){
$scope.tambahData = function() {
//bikin format file json, dari hasil tangkapan form di file add.html
databaru = {
name: $scope.newdata.name,
city: $scope.newdata.city
}
factoryPeople.addPeople(newdata).success(function(result) {
//update data using push method
$scope.listofname.push({
name: $scope.newdata.name,
city: $scope.newdata.city
});
//set form data empty again
$scope.newdata.name= '';
$scope.newdata.city = '';
alert(result);
});
这里是我的add.php:
<?php
header("Access-Control-Allow-Origin: *");
$host = "localhost";
$user = "root";
$pass = "";
$db = "angular";
$link = mysqli_connect($host, $user, $pass, $db) or die(mysqli_error($link));
// get input data
$data = json_decode(file_get_contents("php://input"));
// take value from array
$name= $data['name'];
$city= $data['city'];
// query insert
$sql = "insert into users (name , city) values ('$name', '$city') ";
// echo message
if(mysqli_query($link, $sql)):
echo"input success| name: $name| city: $city";
else: echo"input failed| name : $name | city: $city";
endif;
?>
如果我运行该脚本,数据总是成功地插入到数据库中。 但问题是$ name和$ city没有任何价值。
我不明白为什么。 我错了,使用php_get_contents或什么? 你们能告诉我为了得到更好的结果我应该怎么做?
希望你们能帮助我。
非常感谢。
你检查开发者控制台来查看该请求是否被实际发送的数据? – Terminus