Angular插入数据到MySQL

时间:2016-07-01 15:32:51

标签: php mysql angularjs

我在使用angular。将数据插入MySql DB时遇到问题。

这是我的HTML文件

<!DOCTYPE html>
<html ng-app>
<head>
<title>AngularJs Post Example: DevZone.co.in </title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <style>
        #dv1{
            border:1px solid #DBDCE9; margin-left:auto;
            margin-right:auto;width:220px;
            border-radius:7px;padding: 25px;
        }

        .info{
            border: 1px solid;margin: 10px 0px;
            padding:10px;color: #00529B;
            background-color: #BDE5F8;list-style: none;
        }
        .err{
            border: 1px solid;  margin: 10px 0px;
            padding:10px;  color: #D8000C;
            background-color: #FFBABA;   list-style: none;
        }
    </style>
</head>
<body>
    <div id='dv1'>
        <form ng-controller="FrmController">
            <ul>
                <li class="err" ng-repeat="error in errors"> {{ error}} </li>
            </ul>
            <ul>
                <li class="info" ng-repeat="msg in msgs"> {{ msg}} </li>
            </ul>
            <h2>Sigup Form</h2>
            <div>
                <label>Name</label> 
                <input type="text" ng-model="username" placeholder="User Name" style='margin-left: 22px;'> 
            </div>
            <div>
                <label>Email</label>
                <input type="text" ng-model="useremail" placeholder="Email" style='margin-left: 22px;'> 
            </div>
            <div>
                <label>Password</label>
                <input type="password" ng-model="userpassword" placeholder="Password">
            </div>
            <button ng-click='SignUp();' style='margin-left: 63px;margin-top:10px'>SignUp</button>
        </form>
    </div>

    <script type="text/javascript">
        function FrmController($scope, $http) {
            $scope.errors = [];
            $scope.msgs = [];

            $scope.SignUp = function() {

                $scope.errors.splice(0, $scope.errors.length); // remove all error messages
                $scope.msgs.splice(0, $scope.msgs.length);


                $http.post('http://bloom.net.pl/insertangular/insert.php', {'uname': $scope.username, 'pswd': $scope.userpassword, 'email': $scope.useremail}
                ).success(function(data, status, headers, config) {
                    if (data.msg != '')
                    {
                        $scope.msgs.push(data.msg);
                    }
                    else
                    {
                        $scope.errors.push(data.error);
                    }
                }).error(function(data, status) { // called        asynchronously if an error occurs
// or server returns response with an error status.
                    $scope.errors.push(status);
                });
            }
        }
    </script>

</body>

这是我的插入脚本

<?php
$data = json_decode(file_get_contents("php://input"));
$usrname = mysql_real_escape_string($data->uname);
$upswd = mysql_real_escape_string($data->pswd);
$uemail = mysql_real_escape_string($data->email);

$con = mysql_connect("localhost","testvip1_kol","MoLg67mf");
mysql_select_db("testvip1_kol");
mysql_query("SET NAMES 'utf8'");



$qry_em = 'select * from users where email ="' . $uemail . '"';
$qry_res = mysql_query($qry_em);
$res = mysql_fetch_assoc($qry_res);

if ($res['cnt'] == 0) {
$qry = 'INSERT INTO users (name,pass,email) values ("' . $usrname . '","' . $upswd . '","' . $uemail . '")';
$qry_res = mysql_query($qry);
if ($qry_res) {
    $arr = array('msg' =>  "User Created Successfully!!!", 'error' => '');
    $jsn = json_encode($arr);
    print_r($jsn);
} else {
    $arr = array('msg' => "", 'error' => 'Error In inserting record');
    $jsn = json_encode($arr);
    print_r($jsn);
}
} else {
$arr = array('msg' => "", 'error' => 'User Already exists with same     email');
$jsn = json_encode($arr);
print_r($jsn);
}

?>

问题是我可以向我的数据库插入空行。你能知道如何纠正它吗?

3 个答案:

答案 0 :(得分:0)

如果任何字段为空,您可以阻止用户提交表单。将属性required添加到输入元素,添加按钮类型并将ng-submit添加到表单元素以在提交时触发方法调用而不是单击:

<form ng-controller="FrmController" ng-submit="SignUp()">
  <ul>
    <li class="err" ng-repeat="error in errors"> {{ error}} </li>
  </ul>
  <ul>
    <li class="info" ng-repeat="msg in msgs"> {{ msg}} </li>
  </ul>
  <h2>Sigup Form</h2>
  <div>
    <label>Name</label>
    <input type="text" ng-model="username" placeholder="User Name" style='margin-left: 22px;' required>
  </div>
  <div>
    <label>Email</label>
    <input type="text" ng-model="useremail" placeholder="Email" style='margin-left: 22px;' required>
  </div>
  <div>
    <label>Password</label>
    <input type="password" ng-model="userpassword" placeholder="Password" required>
  </div>
  <button type='submit' style='margin-left: 63px;margin-top:10px'>SignUp</button>
</form>

您可以在SignUp方法中添加额外的验证,并仅在所有字段都有值时提交数据。

编辑: 添加内容类型标题:

$http({
      method: 'post',
      url: 'http://bloom.net.pl/insertangular/insert.php',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      data: {
        'uname': $scope.username,
        'pswd': $scope.userpassword,
        'email': $scope.useremail
      }).success(function(data, status, headers, config) {
      if (data.msg != '') {
        $scope.msgs.push(data.msg);
      } else {
        $scope.errors.push(data.error);
      }
    }).error(function(data, status) { // called        asynchronously if an error occurs
      // or server returns response with an error status.
      $scope.errors.push(status);
    });

答案 1 :(得分:0)

字段在两个文件之间的连接之间存在值问题。

使用

    警报($ scope.username,);

我可以显示此字段值。 php文件中的变量没有值。

答案 2 :(得分:0)

这段代码可能适合你。因为它总是对我而言

<div  ng-controller="FrmController">
<form ng-submit="signUp(user)"> <!-- You can also add formname.$valid for extra validation-->
        <ul>
            <li class="err" ng-repeat="error in errors"> {{ error}} </li>
        </ul>
        <ul>
            <li class="info" ng-repeat="msg in msgs"> {{ msg}} </li>
        </ul>
        <h2>Sigup Form</h2>
        <div>
            <label>Name</label> 
            <input type="text" ng-model="user.username" placeholder="User Name" style='margin-left: 22px;'> 
        </div>
        <div>
            <label>Email</label>
            <input type="text" ng-model="user.email" placeholder="Email" style='margin-left: 22px;'> 
        </div>
        <div>
            <label>Password</label>
            <input type="password" ng-model="user.password" placeholder="Password">
        </div>
        <button type="submit" style='margin-left: 63px;margin-top:10px'>SignUp</button>
    </form>
</div>

控制器中的注册功能

$scope.SignUp = function(data) {
 var $data = angular.toJson(data);
 $http.post('url to the file',$data).then(function(data){
   console.log(data.data);
});
}

在PHP文件中

$data = json_decode(file_get_contents("php://input"));
echo json_encode($data);

您将在控制台上看到所需的数据,然后您可以进行简单的SQL查询以将其推送到数据库中。