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. 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.
Since it's just for learning purposes, I named the database and the table "test".
I am using PHP as the server language.
I have:
- An index.html file for the view
- A script.js file where I use AngularJS HTTP POST method to insert data into the MySQL database
- A config.php file where I deal with the connection with the server and the insertion of data into the database.
Also, my table consists of only 3 columns: an ID (unique, auto-incremented), a "name"(text) and an "age"(int).
The code for each file is here:
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
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
<?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. I have no idea why and I don't find an answer online.