Skip to content

Instantly share code, notes, and snippets.

@FernandoBasso
Created May 19, 2016 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FernandoBasso/34476be04cdaa8b46c7368067aac51b8 to your computer and use it in GitHub Desktop.
Save FernandoBasso/34476be04cdaa8b46c7368067aac51b8 to your computer and use it in GitHub Desktop.
Example of PDO transaction with insertion in two tables and a loop on the second one.
<?php
public function salvaPedidoDb() {
try {
$this->db->beginTransaction();
$sql1 = 'INSERT INTO pedidos (pessoa_fk, preco_total) VALUES (:pessoa_fk, :preco_total)';
$sth1 = $this->db->prepare($sql1);
$sth1->bindParam(':pessoa_fk', $_SESSION['shop_login_pk'], PDO::PARAM_STR);
$sth1->bindParam(':preco_total', $_SESSION['preco_total'], PDO::PARAM_STR);
$sth1->execute();
$pedidoInsertId = $this->db->lastInsertId();
$sql2 = "INSERT INTO itens_pedido (
pedido_fk
, cod_produto
, descricao
, quantidade
, preco_atacado
, preco_varejo
) VALUES (
:pedido_insert_id
, :cod_produto
, :descricao
, :quantidade
, :preco_atacado
, :preco_varejo
)";
$sth2 = $this->db->prepare($sql2);
$len = count($_SESSION['cart']);
for ($i = 0; $i < $len; ++$i) {
$item = $_SESSION['cart'][$i];
$sth2->bindParam(':pedido_insert_id', $pedidoInsertId, PDO::PARAM_INT);
$sth2->bindParam(':cod_produto', $item['pk'], PDO::PARAM_INT);
$sth2->bindParam(':descricao', $item['descricao'], PDO::PARAM_STR);
$sth2->bindParam(':quantidade', $item['qtde'], PDO::PARAM_INT);
$sth2->bindParam(':preco_atacado', $item['preco_atacado'], PDO::PARAM_STR);
$sth2->bindParam(':preco_varejo', $item['preco_atacado'], PDO::PARAM_STR);
$status = $sth2->execute();
if (!$status) break;
}
// Se deu o brak com o status false, returna false por que deu algo errado.
if (!$status) {
return false;
}
$this->db->commit();
return true;
}
catch (PDOException $err) {
$this->db->rollBack();
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment