Skip to content

Instantly share code, notes, and snippets.

@davidchc
Created April 19, 2018 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davidchc/62688b21663f289822c73980d052789e to your computer and use it in GitHub Desktop.
Save davidchc/62688b21663f289822c73980d052789e to your computer and use it in GitHub Desktop.
Criar o pedido com dados do carrinho
<?php
session_start();
require_once "functions/product.php";
require_once "functions/cart.php";
require_once "functions/order.php";
$pdoConnection = require_once "connection.php";
//Simular os dados vindo do formulário do cliente
$customer = array();
$customer['name'] = 'Miguel';
$customer['email'] = 'miguel@gmail.com';
//Dados do Carrinho
$cartProducts = getContentCart($pdoConnection);
//Criar o pedido
if(createOrder($pdo, $$customer, $cartProducts)) {
header("location: success.php");
exit;
}
echo "Erro ao tenta realizar o pedido"
<?php
/*******************************************************
* functions/order.php
* AS TABELAS PRA SALVAR OS PEDIDOS
* TABLE orders
id INTEGER
name VARCHAR (100)
email VARCHAR (100)
status INTEGER
created DATETIME
modified DATETIME
TABLE orders_items
id INTEGER
order_id VARCHAR (100)
product_id VARCHAR (100)
quantity INTEGER
price DECIMAL(10,2)
subtotal DECIMAL(10,2)
*******************************************************
*/
/**
* Criar pedido
*/
function createOrder($pdo, $customer, $cartProducts){
/**
* SQL para salvar as informações do pedido
*/
$sql = "INSERT INTO orders SET name = :name, email = :email, status = :status, created = NOW(), modified = NOW()";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':name', $customer['name']);
$stmt->bindValue(':email', $customer['name']);
$stmt->bindValue(':status', 1);
if(!$stmt->execute()) {
return false;
}
//Recupera o ID inserido
$order_id = $pdo->lastInsertId();
/**
* SQL para inserir os produtos do pedido
*/
$sql = "INSERT INTO orders_items SET order_id = :order_id, product_id = :product_id, quantity = :quantity, price = :price, subtotal = :subtotal";
$stmt = $pdo->prepare($sql);
foreach($cartProducts as $cart) {
$stmt->bindValue(':order_id', $order_id);
$stmt->bindValue(':product_id', $cart['id']);
$stmt->bindValue(':quantity', $cart['quantity']);
$stmt->bindValue(':price', $cart['price']);
$stmt->bindValue(':subtotal', $cart['subtotal']);
if(!$stmt->execute()) {
return false;
}
}
return true;
}
/**
* Retorna todos os pedidos
*/
function getOrders($pdo) {
$sql = "SELECT *, (SELECT SUM(oi.subtotal) FROM orders_items oi WHERE oi.order_id - o.id ) AS total
FROM orders o ";
$stmt = $pdo->prepare($sql);
$stmt->execute();
return $stmt->fetchAll(\PDO::FETCH_ASSOC);
}
<?php
echo 'Seu pedido foi criado com sucesso.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment