将数组JSON放入MySQL并返回数组

5

字段 'cats' 是 Angular 应用程序中的选择框,包含来自表格 cats 的数据,其中包括 id、name 和 module_id。

在 Slim 框架上添加项目的函数。

function addItem($section) {

  $request = \Slim\Slim::getInstance()->request();
  $item = json_decode($request->getBody());

  $sql = "INSERT INTO " .$section. " (title, subtitle, slug, excerpt, originalDate, content, cats, published) VALUES (:title, :subtitle, :slug, :excerpt, :originalDate, :content, :cats, :published)";

  try {
      $db = getConnection();
      $stmt = $db->prepare($sql);

      $stmt->bindParam("title", $item->title);
      $stmt->bindParam("subtitle", $item->subtitle);
      $stmt->bindParam("slug", $item->slug);
      $stmt->bindParam("excerpt", $item->excerpt);
      $stmt->bindParam("originalDate", $item->originalDate);
      $stmt->bindParam("content", $item->content);
      $stmt->bindParam("cats", $item->cats);
      $stmt->bindParam("published", $item->published);

      $stmt->execute();
      $item->id = $db->lastInsertId();
      $db = null;

      print_r(json_encode($item));
  } 
  catch(PDOException $e) {
      echo '{"error":{"text":'. $e->getMessage() .'}}';
  }
}

Angular代码,用于选择框

<div class="col-sm-12 m-b-30">
  <p class="f-500 c-black m-b-15">Categorias</p>
  <div class="btn-group bootstrap-select show-tick">
    <button type="button" class="btn selectpicker btn-default" ng-model="item.cats" data-toggle="dropdown" title="Selecione a Categoria" aria-expanded="false" data-html="1" data-multiple="1" bs-options="cats.id as cats.name for cats in categorias" bs-select>
      Selecione a categoria <span class="caret"></span>
    </button>

  </div>
</div>

猫,返回mysql列上的数组

有什么想法?!

在线示例:http://45.55.73.98/angular-admin/api/v1/s/posts

已更新!

$cats = null;
foreach ($item->cats as $cat) {
    $cats .= $cat . ",";
}

并且

$stmt->bindParam("cats", $cats);

我现在添加了代码,JSON响应在这个最后的链接中。 - Marco Riesco
@MarcoRiesco 你能加上你的Angular控制器代码吗? - Davide Pastore
1
感谢所有回复的人,我今天早上得到了答案。我会在这里发布结果。 - Marco Riesco
13
使用implode函数将$item->cats数组转换成字符串"$cats"要比使用循环更容易。 - Markus Zeller
4
如果您已经按照上述所述获得了答案,请在此处发布并接受自己的答案。不要保持问题的开放状态。谢谢。 - dchayka
显示剩余2条评论
1个回答

1

正如评论中所述,并且在问题的编辑中提供了解决方案,我只是在这里放置答案(根据评论中的建议进行修改)。

this->cats 是一个数组 - 首先使用以下方法将其转换为字符串:

$cats=implode(',',$item->cats);

然后将其绑定:

$stmt->bindParam("cats", $cats);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接