php - 在 AngularJS 中捕获 PDO 异常

标签 php mysql angularjs pdo

所以我在 AngularJS+PHP+MySQL 中制作了一个 SignUP 表单,现在我想在我的 Angular 中捕获 PDO 异常,这样我就可以创建一个 IF 重复条目,例如“登录”,我可以在我的 Angular 中打印出来,但是我不知道从哪里开始。我用谷歌搜索了一下,但找不到任何真正有用的东西。

这是我的.controller:

.controller('registerController', function($scope, $http) {
  $scope.registerData = {firstname : null, lastname : null, login: null, password : null, email : null, city : null, postalcode : null, adress: null, country: null};

  $scope.registerFunction = function() {
    $http({
        method: "post",
        url: './php/registration.php',
        data: {
            firstname: $scope.registerData.firstname,
            lastname: $scope.registerData.lastname,
            login: $scope.registerData.login,
            password: $scope.registerData.password,
            email: $scope.registerData.email,
            city: $scope.registerData.city,
            postalcode: $scope.registerData.postalcode,
            adress: $scope.registerData.adress,
            country: $scope.registerData.country,
        },
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
    swal("Good job!", "You have been registered!", "success");
  };
})

这是我在 html+bootstrap 中的 form :

  <div class="modal fade" id="registerModal">
    <div class="modal-dialog">
      <div class="modal-content" ng-controller="registerController">
        <div class="modal-header"><h4 class="modal-title">Sign Up</h4></br><button type="button" class="close" data-dismiss="modal">&times;</button></div>
        <div class="modal-body"><form>
            <div class="row">
                <div class="col-lg-6">
                  <label style="float: left;"><b>Firstname:</b></label>
                  <input type="text" ng-model="registerData.firstname" class="form-control">
                  <label style="float: left;"><b>Lastname:</b></label>
                  <input type="text" ng-model="registerData.lastname" class="form-control">
                  <label style="float: left;"><b><span class="redstar">*</span> Login:</b></label>
                  <input type="text" ng-model="registerData.login" class="form-control">
                  <label style="float: left;"><b><span class="redstar">*</span> Password:</b></label>
                  <input type="password" ng-model="registerData.password" class="form-control">
                  <label style="float: left;"><b><span class="redstar">*</span> Repeat Password:</b></label>
                  <input type="password" class="form-control">
                </div>
                <div class="col-lg-6">
                  <label style="float: left;"><b><span class="redstar">*</span> E-Mail:</b></label>
                  <input type="text" ng-model="registerData.email" class="form-control">
                  <label style="float: left;"><b>City:</b></label>
                  <input type="text" ng-model="registerData.city" class="form-control">
                  <label style="float: left;"><b>Postal Code:</b></label>
                  <input type="text" ng-model="registerData.postalcode" class="form-control">
                  <label style="float: left;"><b>Adress:</b></label>
                  <input type="text" ng-model="registerData.adress" class="form-control">
                  <label style="float: left;"><b>Country:</b></label>
                  <select class="form-control" ng-model="registerData.country" required>
                    <option ng-repeat="item in countries" value="{{item.id}}">
                      {{item.name}}
                    </option>
                  </select>
                </div>
                <div class="col-lg-12">
                  <p style="float:left;">Fields marked with <span class="redstar"><b>*</b></span> are required.</p></br>
                </div>
            </div>
        </form></div>
        <div class="modal-footer"><button type="button" class="btn btn-danger" data-dismiss="modal">Close</button><button type="button" class="btn btn-success" data-dismiss="modal" ng-click="registerFunction()">Sign Up</button></div>
        </div></div>
    </div>

我是这样执行的:

<?php
include_once 'config.php';
$data = json_decode(file_get_contents("php://input"));

$firstname = $data->firstname;
$lastname = $data->lastname;
$login = $data->login;
$password = $data->password;
$email = $data->email;
$city = $data->city;
$postalcode = $data->postalcode;
$adress = $data->adress;
$country = $data->country;

$dbh->query("INSERT INTO `accounts` (`account_id`, `firstname`, `lastname`, `login`, `password`, `email`, `city`, `postalcode`, `adress`, `country`, `role`)
    VALUES (NULL,'".$firstname."','".$lastname."','".$login."',MD5('".$password."'),'".$email."','".$city."','".$postalcode."','".$adress."','".$country."', 0) ") or die(mysql_error());
$dbh = null;
?>

这是我的连接:

<?php
$hostname='localhost';
$username='root';
$password='';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=myshop",$username,$password);

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
    echo 'Connected to Database';
}
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?>

我的问题是,例如,我如何在我的 Controller 中添加和If,就像“登录”的错误重复条目一样,我在我的 Angular 做了一些事情。那么我怎样才能将错误捕获到我的 Controller 中呢?

最佳答案

除了@deceze 的出色回答之外,还有一件事需要解释。

有两种异常:预期的和意外的。他们应该受到区别对待。

您要求的是预期的。已使用的用户名是常规情况,从应用程序的 Angular 来看,我不会将其称为错误。所以响应也应该是有规律的。应该向 Angular 发送一条有意义的消息,后者应该采取相应的行动:提示用户尝试另一个用户名。

另一件事是意外错误。比如你的数据库服务器宕机了。对于这种错误,不应显示特定的错误消息,而应显示通用的借口和稍后再试的建议。

现在开始实现:您应该捕获预期的错误,否则不应该捕获

一个例子可以在我的PDO tutorial中看到:

try {
    $pdo->prepare("INSERT INTO users VALUES (NULL,?,?,?,?)")->execute($data);
} catch (PDOException $e) {
    $existingkey = "Integrity constraint violation: 1062 Duplicate entry";
    if (strpos($e->getMessage(), $existingkey) !== FALSE) {
        // Take some action if there is a key constraint violation, i.e. duplicate name
    } else {
        throw $e;
    }
}

在这里您可以看到捕获的异常应该根据预期错误列表进行测试,如果没有匹配则重新抛出 id。

关于php - 在 AngularJS 中捕获 PDO 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49316057/

相关文章:

php - 数据未显示在选项卡中

mysql - 从多列中选择最小值然后计算它们的总和的最佳方法是什么?

php - Laravel API - AngularJS : Access-Control-Allow-Origin error

c# - 每当数据库更新时更新 C# 客户端

javascript - 如何在 ng-repeat 中显示接下来的 15 个项目?

ajax - 上传 Angularjs 之前预览图像

php - 从 Laravel 命令中清除控制台

php - 如何使用可选参数调用存储过程

javascript - getelementbyid 仅适用于 php while 循环中的第一个 id

mysql - 环回 : how do I make sure that values are sent to the local db, 不是远程数据库?