Pass array object to API and save to Database

Asked

Viewed 262 times

0

I’m using Ionic 3 and I want to save the data of an object in the database. In the API is running the query and saving null in the database, I imagine the way I am sending the object is wrong. Follow my code:

finaliza(obj){    
    this.pedido.push(this.prod);

      let headers = new Headers();

      headers.append('Content Type', 'application/json');

      let options = new RequestOptions({headers: headers});

      this.service.postData().subscribe(
        data =>obj=data,
        err =>console.log(err)
      );
    }
In the preview:

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class ProdutosProvider {

api:string='http://mywebsite.com/';

  constructor(public http: Http) {
    console.log('Hello ProdutosProvider Provider');
  }
  
  getData(){
    return this.http.get(this.api +'app-produtos.php').map(res=> res.json())
  }

  postData(){
    return this.http.get(this.api +'app-pedidos.php').map(res=> res.json())
  }


}

This object is coming from the normal database and in the API for insertion I am using the following code:

<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: text/html; charset=utf-8');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");


$dns = "mysql:host=localhost;dbname=mydb";
$user = "myuser";
$pass = "mypass";

try {
        $data = file_get_contents("php://input");
        $objData = json_decode($data);
       
        $id = $objData->id;
        $name = $objData->name;
        $img = $objData->img;
        
       
        // LIMPA OS DADOS
        $id = stripslashes($id);
        $name = stripslashes($name);
        $img = stripslashes($img);
        
        $id = trim($id);
        $name = trim($name);
        $img = trim($img);        
        

    $con = new PDO($dns, $user, $pass);
    if(!$con){
        echo "Não foi possivel conectar com Banco de Dados!";
    }
    
        $conn = mysqli_connect('localhost','myuser','mypass','mydb');
        $sql1 = "INSERT into pedidos_app (id,id_prod,name,img) values (null,'{$id}','{$name}','{$img}')";
        $qr1=mysqli_query($conn,$sql1);      
    
        
} catch (Exception $e) {
    echo "Erro: ". $e->getMessage();
};

  • you are using angular? You can provide more details of javascript code?

  • @Andréluizdegusmão, I am using Angular 3 / Inioc 3, the rest of the script is normal, because it works in another API, the problem is in the form of sending, which is within the mentioned code function

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.