Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put Array json on mysql return Array

Field 'cats' is a selectbox from Angular app, contain data from table cats, with id, name and module_id.

function on Slim framework for add items..

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 code, for select box

<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>

cats, return Array on mysql column

Any ideas?!

Example online: http://45.55.73.98/angular-admin/api/v1/s/posts

Updated!

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

and

$stmt->bindParam("cats", $cats);
like image 887
Marco Riesco Avatar asked Nov 09 '22 10:11

Marco Riesco


1 Answers

As stated in the comments and the solution is provided in the edit of the question, I am just putting the answer here (modified as suggested in the comment).

the this->cats is an array - first convert him to string with:

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

and then bind him:

$stmt->bindParam("cats", $cats);
like image 88
2 revs, 2 users 82% Avatar answered Nov 14 '22 23:11

2 revs, 2 users 82%