How to perform an Insert or update of a JSON object

Asked

Viewed 1,028 times

4

JSON object $postdata:

{
    "0": {
        "codigo": "1",
        "descricao": "Bobina",
        "preco": "10.0000"
    },
    "1": {
        "codigo": "2",
        "descricao": "Capa",
        "preco": "20.0000"
    }
}

Using Mysql, how to perform insert if there is no or update if registered in the BD?

Editing:

The attribute [code, description and price] of each item ["0", "1"] will be inserted in the database in its respective column.

Edition II:

$postdata = file_get_contents("php://input"); 
$request = json_decode($postdata); 
$id = $request->id; ...
  • Relax there, your column is of the json type? or you want to play the json information for the bank (separating the values in the respective columns)?

  • Hello @rray, I edited the question.

  • In the part of the price 10 and 20 what is the real value there is 20 real and 10 real?

  • 1

    Yes, @Virgilionovic are fictional values.

2 answers

3


Do as follows, with Object Orientation:

Class database

<?php

class database extends PDO
{
    public function __construct($dsn='mysql:host=127.0.0.1;dbname=new_schema',
                                $user='root',
                                $pass='senha')
    {
        parent::__construct($dsn, $user, $pass);
    }
}

Class data

<?php

class data
{
    private $codigo;
    private $descricao;
    private $preco;

    public function __construct($codigo = 0, $descricao = '', $preco = 0)
    {
        $this->codigo = $codigo;
        $this->descricao = $descricao;
        $this->preco = $preco;
    }

    public function getCodigo()
    {
        return $this->codigo;
    }
    public function setCodigo($codigo)
    {
        $this->codigo = $codigo;
        return $this;
    }
    public function getDescricao()
    {
        return $this->descricao;
    }
    public function setDescricao($descricao)
    {
        $this->descricao = $descricao;
        return $this;
    }
    public function getPreco()
    {
        return $this->preco;
    }
    public function setPreco($preco)
    {
        $this->preco = $preco;
        return $this;
    }

}

Class daoData

<?php

class daoData
{
    private $database;
    public function __construct(database $database)
    {
        $this->database = $database;
    }

    public function insert(data $data)
    {
        $stmt = $this->database
            ->prepare('INSERT INTO tb_data(codigo, descricao, preco) VALUES(?,?,?)');

        $stmt->bindValue(1, $data->getCodigo());
        $stmt->bindValue(2, $data->getDescricao());
        $stmt->bindValue(3, $data->getPreco());

        $result = $stmt->execute();
        $stmt->closeCursor();

        return $result;
    }
    public function update(data $data)
    {
        $stmt = $this->database
            ->prepare('UPDATE tb_data SET descricao=?, preco=? WHERE codigo=?');

        $stmt->bindValue(1, $data->getDescricao());
        $stmt->bindValue(2, $data->getPreco());
        $stmt->bindValue(3, $data->getCodigo());

        $result = $stmt->execute();
        $stmt->closeCursor();

        return $result;
    }

    public function insertOrUpdate(data $data)
    {
        $stmt = $this->database->prepare('SELECT COUNT(*) FROM tb_data WHERE codigo=?');
        $stmt->bindValue(1, $data->getCodigo());
        if ($stmt->execute())
        {
            $result = $stmt->fetchColumn(0);
            $stmt->closeCursor();
            return $result == 0 ?
                $this->insert($data) :
                $this->update($data);
        }
        return false;
    }
}

index.php

<?php

require 'database.php';
require 'data.php';
require 'daodata.php';

$json = '{
    "0": {
        "codigo": "1",
        "descricao": "Bobina",
        "preco": "10.0000"
    },
    "1": {
        "codigo": "2",
        "descricao": "Capa",
        "preco": "20.0000"
    }
}';

$dataJson = json_decode($json, true);    

$database = new database();

$dao = new daoData($database);

foreach($dataJson as $key => $item)
{
    $data = new data($item['codigo'],
        $item['descricao'],
        $item['preco']);
    $dao->insertOrUpdate($data);
}

1

First you have to convert JSON to a PHP object or array using the json_encode() - http://php.net/json_encode

Then check in the bank if the ids exist, if they already exist in the bank make a UPDATE, but a INSERT.

  • If you want a more specific answer, go through these steps and at each difficulty ask a new question with a specific problem, so open questions are complicated to answer.

  • Marcos, I’ve got the following: $postdata = file_get_contents("php://input");&#xA;$request = json_decode($postdata);&#xA;$id = $request->id; ...

  • Great, for ease, edit your question and put the code you already have there.

Browser other questions tagged

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