Do the following 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);
}