Created
May 17, 2017 01:19
-
-
Save davidchc/38c9bd9aa8920abee33176d6e74abdbd to your computer and use it in GitHub Desktop.
Exemplo de retornar dados do carrinho de compra usando funções
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
session_start(); | |
require_once "cart-functions.php"; | |
$itemsCart = getCartContent(); | |
$totalCart = getCartTotal(); | |
?> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//função pra criar conexao com banco de dados | |
function getPDOConnection() { | |
static $connection; | |
if(!$connection) { | |
$connection = new PDO("mysql:host=localhost;dbname=mxmasters", "root", ""); | |
} | |
return $connection; | |
} | |
//funcao pra retornar os produtos do carrinho | |
function getCartContent(){ | |
$result = array(); | |
if(!$_SESSION['carrinho']) { | |
return $result; | |
} | |
//atribuir os itens do carrinho a variavel cart | |
$cart = $_SESSION['carrinho']; | |
//Pega os ids do produtos do carrinho | |
$ids = array_keys($cart); | |
//Retorna a instancia do PDO | |
$pdo = getPDOConnection(); | |
//cria o SQL para pesquisar os produtos | |
$sql = "SELECT * FROM produtos WHERE FIND_IN_SET(id, :ids) "; | |
//prepare SQL | |
$stmt = $pdo->prepare($sql); | |
//Adiciona o valor ao placeholder :ids | |
$stmt->bindValue(':ids', implode(",", $ids)); | |
//Executa o SQL | |
$stmt->execute(); | |
//Retorna todos os produtos | |
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); | |
//percorre todos os produtos | |
foreach($rows as $row) { | |
// id do produto | |
$id = $row['id']; | |
//nome do produto | |
$name = $row['nome']; | |
//quantidade do produto | |
$quantity = $cart[$id]; | |
//valor do produto | |
$price = $row['preco']; | |
//subtotal do produto | |
$subTotal = $price * $quantity; | |
//array contendo as informacoes do carrinho | |
$result[] = array( | |
'id' => $id, | |
'name' = $name, | |
'quantity' = $quantity, | |
'price' = $price, | |
'subTotal' = $subTotal, | |
); | |
} | |
return $result; | |
} | |
//Função que retorna o valor total do carrinho | |
function getCartTotal() { | |
$results = getCartContent(); | |
$total = 0; | |
foreach($results as $result) { | |
$total += $result['subTotal']; | |
} | |
return $total; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment