Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

So, I'm new to AngularJS and I was trying to do a simple web page to add values to a MySQL database with PHP. Here is the HTML:

<DOCTYPE html>  
<html lang="pt">
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<script src="js/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="js/pannel.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css"/>
<link rel="stylesheet" href="css/pannel.css" type="text/css"/>
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container-fluid">
  <div class="navbar-header">
    <a class="navbar-brand" href="index.html">Garagi Extreme</a>
  </div>
  <div>
    <ul class="nav navbar-nav">
      <li class="active">
        <a href="#">Inserir Carro</a>
      </li>
      <li><a href="#">Alterar/excluir Carro</a></li>
      <li><a href="#">Inserir Montadora</a></li>
      <li><a href="#">Alterar/excluir Montadora</a></li>
    </ul>
  </div>
</div>
</nav>
<div ng-app="garagem" ng-controller="montadora">
  <form>
    <p>Nome da Montadora: <input type="text" ng-model="nomeMont"/></p>
    <input type="button" ng-click="insertMontadora()" value="Enviar" class="btn primary-btn"/>
  </form>
</div>

</body>
</html>

And My pannel.js:

var app= angular.module('garagem', []);
app.controller('montadora',["$scope", "$http", function ($scope, $http) {
$scope.insertMontadora=function () {
$http.post("db/insertMont.php", {'nomeMont': $scope.nomeMont})
.success(function (data,status,headers,config) {
  console.log("Inserted");
});
}
}]);

And my PHP page to connect to the database and make the query:

$nomeMont=mysql_real_escape_string($data->nomeMont);

$local_server="localhost";
$usuario= "tkc";
$senha="185478";
$banco="garagiextrem";

mysql_connect($local_server, $usuario, $senha) or die("Nope");
mysql_select_db($banco) or die("Nain");
mysql_query('INSERT INTO montadora(idMontadora,Nome) VALUES ("NULL",'" . $nomeMont . "')');
 ?>

When I load the page on a browser, everything works just fine, and I even get the "Inserted" message on the console. But when I go check the phpMyAdmin, there is no entries on the table. What am I doing wrong here? :(

share|improve this question
    
You're not checking the success or failure of mysql_query (or other function calls). Try checking for errors rather than assuming everything just works. Also, you should use mysqli since mysql is depreciated and will be removed from future releases of php. – Tristan Dec 6 '15 at 1:12
    
For the mysql instead of mysqli or PDO, I'm following an old tutorial, apparently XD. But could you tell me how can I check for this errors in the query? Sorry, I'm a noob, haha – MatheusFongaro Dec 6 '15 at 1:51
    
Write out mysql errors to at text file. Maybe there is an error. – Kohjah Breese Dec 6 '15 at 2:30
up vote 0 down vote accepted

If you check for any errors backend you can send the result and display an appropriate message within Angular.

The below php code uses mysqli functions and checks for errors that may arise.

Assuming idMontadora is the primary key of your table and it is auto incrementing, you don't need to include it in the insert query.

I would recommend using output buffering because any notices will dirty the json returned to Angular. See the use of ob_start() at the top of the script, and ob_clean() immediately before the json is echoed.

I have written a little function to handle the echo of the result process_output() to avoid code duplication.

<?php
// start output buffering
ob_start();

// utility function to clean output and echo as json
function process_output($result, $msg)
{
    $out = array('result' => $result, 'msg' => $msg);
    ob_clean();
    echo json_encode($out, JSON_NUMERIC_CHECK);
    exit();
}

$local_server="localhost";
$usuario= "tkc";
$senha="185478";
$banco="garagiextrem";
// setup mysqli
$mysqli = new mysqli($local_server, $usuario, $senha, $banco);
// check connection
if ($mysqli->connect_errno) 
    process_output(0, "Connect failed: ".$mysqli->connect_error);
// define the query
$sql ="INSERT INTO montadora (Nome) VALUES (?)";
// prepare the query
if (!$stmt = $mysqli->prepare($sql)) 
    process_output(0, "Prepare failed: ".$stmt->error);
// bind the parameter
if (!$res = $stmt->bind_param('s', $data->nomeMont))
    process_output(0, "Bind failed: ".$stmt->error);
// execute
if (!$res = $stmt->execute())
    process_output(0, "Execute failed: ".$stmt->error);
// no errors so return true
process_output(1, "Rows inserted: ".$stmt->affected_rows);

In your Angular controller you can then use the result to debug what is happening backend, and also to display an appropriate message to the user, etc.

The below just console logs the data received from the $http.post, but you can extend it to handle the success or error appropriately.

var app= angular.module('garagem', []);
app.controller('montadora',["$scope", "$http", function ($scope, $http) {
    $scope.insertMontadora=function () {
        $http.post("db/insertMont.php", {'nomeMont': $scope.nomeMont}).then(
            function (data,status,headers,config) {
                console.log(data);
            },
            function(data, status, headers, config) {
                console.log(data);
                console.log(status);
            }
        );
    };
}]);

The backend sends the msg which tells you what has happened, and the result key that can be easily used to setup error handling in the controller. Eg. if (data.result === 0) { // handle the error }

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.