简体   繁体   English

HTTP Post方法不适用于AngularJS + PHP + MySQL

[英]HTTP Post method does not work with AngularJS + PHP + MySQL

Although I found other topics reporting the same issue, none of them helped me. 尽管我发现其他主题报告了相同的问题,但是它们都没有帮助我。

I'm learning AngularJS and I tried to insert data into a MySQL database. 我正在学习AngularJS,并尝试将数据插入MySQL数据库。 I have a really simple HTML file where the user can provide a name and age, and then click in a Submit button which would put this data into the MySQL database. 我有一个非常简单的HTML文件,用户可以在其中提供名称和年龄,然后单击“提交”按钮,该按钮会将这些数据放入MySQL数据库。

Since it's just for learning purposes, I named the database and the table "test". 由于只是出于学习目的,因此我将数据库和表命名为“ test”。

I am using PHP as the server language. 我正在使用PHP作为服务器语言。 I have: 我有:
- An index.html file for the view -该视图的index.html文件
- A script.js file where I use AngularJS HTTP POST method to insert data into the MySQL database -一个script.js文件,我使用AngularJS HTTP POST方法将数据插入MySQL数据库
- A config.php file where I deal with the connection with the server and the insertion of data into the database. -一个config.php文件,其中处理与服务器的连接以及将数据插入数据库中。

Also, my table consists of only 3 columns: an ID (unique, auto-incremented), a "name"(text) and an "age"(int). 而且,我的表仅由3列组成:ID(唯一,自动递增),“名称”(文本)和“年龄”(int)。

The code for each file is here: 每个文件的代码在这里:

index.html 的index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>AngularJS-PHP-MySQL</title>
    <!-- AngularJS CDN-->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <!-- script.js with implementation of Module and Controller -->
    <script src="script.js" ></script>
  </head>
  <body>

<div ng-app="myApp" ng-controller="formCtrl">
  <form id="myForm" action="" method="post">
    <input type="text" name="name" id="name" value="" placeholder="Name" ng-model="nameModel">
    <input type="text" name="age" id="age" value="" placeholder="Age" ng-model="ageModel">
    <input type="button" name="sub" id="sub" value="Submit" ng-click="insertData()">
  </form>
</div>


  </body>
</html>

script.js 的script.js

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope,$http){
  $scope.insertData = function(){
    $http.post("config.php",{'name': $scope.nameModel, 'age': $scope.ageModel})
        .success(function(data, status, headers, config){
            console.log("inserted Successfully");
        });
    }
});

config.php config.php文件

<?php
$servername   = "127.0.0.1";
$username     = "root";
$password     = "";
$Table_name   = "test";

mysql_connect($servername, $username, $password);
mysql_select_db($Table_name) or die(mysql_error());

$name = $_POST['name'];
$age = $_POST['age'];

mysql_query("INSERT INTO $Table_name('name', 'age') VALUES('$name', '$age')");

?>

I get an alert that the POST method was successful but it did not insert the data into the table. 我收到POST方法成功的警报,但没有将数据插入表中。 I have no idea why and I don't find an answer online. 我不知道为什么,也找不到在线答案。

I found in another topic here that AngularJS and some server side languages like PHP have different ways to serialize and transmit the data. 我在这里的另一个主题中发现,AngularJS和一些服务器端语言(如PHP)具有序列化和传输数据的不同方法。 Like the post says, the problem lies with PHP being unable to understand AngularJS's transmission natively. 就像帖子所说的那样,问题出在PHP无法原生理解AngularJS的传输。

To avoid that, I explicitly built the header on my inserData() function: 为了避免这种情况,我在inserData()函数上显式构建了标题:

script.js 的script.js

var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope,$http){
  $scope.insertData = function(){
    var request = $http({
            method: "post",
            url: "config.php",
            data: {
                name: $scope.nameModel,
                age: $scope.ageModel,
            },
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
  }
}); 

I also changed my config.php file into: 我也将config.php文件更改为:

<?php

$servername         = "127.0.0.1";
$username           = "root";
$password           = "";
$dbname             = "test";

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

$name = $request->name;
$age = $request->age;

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO test(name, age) VALUES('$name', '$age')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
}
else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>

Now they can transmit compatible data. 现在他们可以传输兼容的数据。 I also assigned the connection to a variable and then used it to query my data. 我还将连接分配给变量,然后用它来查询数据。

The HTML remains the same. HTML保持不变。 With these changes, everything here is working properly now. 经过这些更改,此处的所有内容现在都可以正常工作。

I'm not sure if your PHP/MYSQL code is OK. 我不确定您的PHP / MYSQL代码是否正确。

Could you try the following code? 您可以尝试以下代码吗?

<?php
$servername   = "127.0.0.1";
$username     = "root";
$password     = "";
$Table_name   = "test";

$connection = mysql_connect($servername, $username, $password);
mysql_select_db($Table_name, $connection) or die(mysql_error());

$name = $_POST['name'];
$age = $_POST['age'];

$sqlQuery = "INSERT INTO $Table_name('name', 'age') VALUES('$name', '$age')";
mysql_query($sqlQuery, $connection);
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM