【问题标题】:Adding a JSON array to MySQL database using PHP使用 PHP 将 JSON 数组添加到 MySQL 数据库
【发布时间】:2016-02-13 22:41:26
【问题描述】:

我有一个向我的 PHP 发送数组的 AngularJS 函数。但是我如何在 PHP 中遍历这个数组并将每个值插入 MySQL 数据库。所以我有以下 $http 帖子:

var data = {
  "username": $scope.un,
  "courses": $scope.selectedCourses
}

$http({
url: "submitCourses.php",
method: "POST",
 data: data
 }).success(function(response) {
   $scope.courseSubmitResponse = response.resp;

 });

$scope.selectedCourses 在发送时看起来像 ["COEN 10", "MATH 54", "HIST 99"]。那么如何将这些值中的每一个插入到我的数据库中呢?有没有办法可以将 php 变量分配给数组,然后对该 php 变量执行 for 循环?非常感谢您的帮助。

【问题讨论】:

    标签: php mysql angularjs http-post


    【解决方案1】:
    var data = {
      "username": $scope.un,
      "courses": $scope.selectedCourses
    }
    
    $http({
    url: "submitCourses.php",
    method: "POST",
     data: data
     }).success(function(response) {
       $scope.courseSubmitResponse = response[0].resp;
    
     });
    

    仅当响应数组长度为 1 并且如果您有多个记录作为响应,您需要动态获取值时才尝试此代码,可能 for 循环很有用

    【讨论】:

      【解决方案2】:

      我假设从客户端传输到服务器端的数据是 json。

      下面是sn-p:

      $data = json_decode($data, true);
      
      foreach($data as $element) {
          list($subject, $mark) = explode(" ", $element);
          // insert using PDO into the database.
      }
      

      【讨论】:

        【解决方案3】:

        使用以下方式访问您的数据:

        $data         = json_decode(file_get_contents('php://input'));
        
        $user         = $data->username;
        $coursesArray = $data->courses;
        

        然后循环你的课程并做你需要的事情

        【讨论】:

          猜你喜欢
          • 2014-11-11
          • 2017-07-14
          • 2014-01-03
          • 1970-01-01
          • 2012-07-21
          • 2020-02-29
          • 2017-07-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多