Carro de Compras Simple con PHP y MySQL

Si estas buscando una manera sencilla  de un carrito  compra PHP MySQL, entonces este tutorial es para ti. Aquí tienes un fragmento de código para aprender paso a paso a realizar un carro de compras. En este post vamos a aprender cómo hacer una sencilla aplicación de carrito de compra PHP.

Este script PHP  es muy simple de entender a un programador web principiante, es por ello que te será muy fácil de aplicarlo a tus proyectos web.

La funcionalidad del script consiste en mostrar la lista de productos de la base de datos MySQL. En donde para cada producto se presentan las opciones  de introducir la cantidad de artículo a añadir a la cesta de la compra, luego esos artículos  serán almacenados en una variable de sesión los cuales son recuperados posteriormente usando un ciclo foreach.

Se ha utilizado un código php muy básico para la creación de este  carrito de compra mediante el uso de métodos GET y POST de PHP.

carrito

Código fuente:

Base de datos:

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Base de datos: `test`
--

-- --------------------------------------------------------

--
-- Estructura de tabla para la tabla `productos`
--

CREATE TABLE IF NOT EXISTS `productos` (
 `id` int(11) NOT NULL,
 `name` varchar(255) NOT NULL,
 `image` varchar(255) NOT NULL,
 `price` double(10,2) NOT NULL
) ENGINE=MyISAM AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;

--
-- Volcado de datos para la tabla `productos`
--

INSERT INTO `productos` (`id`, `name`, `image`, `price`) VALUES
(1, 'Monitor LED UHD 24" U24E590D', 'http://images.samsung.com/is/image/samsung/es_LU24E590DS-EN_001_Front_black?$DT-Gallery$', 200.00),
(2, 'Monitor LED Curvo 27" C27F591FDU', 'http://images.samsung.com/is/image/samsung/es_LC27F591FDUXEN_001_Front_white?$DT-Gallery$', 588.00),
(3, 'Galaxi note 7', 'http://www.samsung.com/es/consumer/mobile-devices/smartphones/galaxy-note/galaxy-note7/smart-switch/images/apps_smart-switch_banner_img.png', 499.00);

--
-- Índices para tablas volcadas
--

--
-- Indices de la tabla `productos`
--
ALTER TABLE `productos`
 ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT de las tablas volcadas
--

--
-- AUTO_INCREMENT de la tabla `productos`
--
ALTER TABLE `productos`
 MODIFY `id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

index.php

<?php
session_start();
$connect = mysqli_connect("localhost", "root", "", "test");
if(isset($_POST["add_to_cart"]))
{
if(isset($_SESSION["shopping_cart"]))
{
$item_array_id = array_column($_SESSION["shopping_cart"], "item_id");
if(!in_array($_GET["id"], $item_array_id))
{
$count = count($_SESSION["shopping_cart"]);
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][$count] = $item_array;
}
else
{
echo '<script>alert("El producto ya se encuentra agregado")</script>';

}
}
else
{
$item_array = array(
'item_id' => $_GET["id"],
'item_name' => $_POST["hidden_name"],
'item_price' => $_POST["hidden_price"],
'item_quantity' => $_POST["quantity"]
);
$_SESSION["shopping_cart"][0] = $item_array;
}
}
if(isset($_GET["action"]))
{
if($_GET["action"] == "delete")
{
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
if($values["item_id"] == $_GET["id"])
{
unset($_SESSION["shopping_cart"][$keys]);
echo '<script>alert("Producto eliminado")</script>';
echo '<script>window.location="index.php"</script>';
}
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Tutorial | Carro de Compra Simple con PHP y MySQL</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script> 
 	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" /> 
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="width:800px;">
<h3 align="center">Carro de Compra Simple con PHP y MySQL</h3>
<?php
$query = "SELECT * FROM productos ORDER BY id ASC";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
?>
<div class="col-md-4">
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?action=add&id=<?php echo $row["id"]; ?>">
<div class="thumbnail">
<img src="<?php echo $row["image"]; ?>" class="img-responsive" />
<div class="caption">
<h4 class="text-info text-center"><?php echo $row["name"]; ?></h4>
<h4 class="text-danger text-center">$ <?php echo $row["price"]; ?></h4>
<input type="text" name="quantity" class="form-control" value="1" />
<p class='text-center'>
<input type="submit" name="add_to_cart" class="btn btn-success " value="Agregar al carro" /></p>

<input type="hidden" name="hidden_name" value="<?php echo $row["name"]; ?>" />
<input type="hidden" name="hidden_price" value="<?php echo $row["price"]; ?>" />
</div>
</div>
</form>
</div>
<?php
}
}
?>
<div style="clear:both"></div>
<h3>Detalle de la orden</h3>
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th width="40%">Descripción</th>
<th width="10%" class='text-center'>Cantidad</th>
<th width="20%" class='text-right'>Precio</th>
<th width="15%" class='text-right'>Total</th>
<th width="5%"></th>
</tr>
<?php
if(!empty($_SESSION["shopping_cart"]))
{
$total = 0;
foreach($_SESSION["shopping_cart"] as $keys => $values)
{
?>
<tr>
<td><?php echo $values["item_name"]; ?></td>
<td class='text-center'><?php echo $values["item_quantity"]; ?></td>
<td class='text-right'>$ <?php echo $values["item_price"]; ?></td>
<td class='text-right'>$ <?php echo number_format($values["item_quantity"] * $values["item_price"], 2); ?></td>
<td><a href="index.php?action=delete&id=<?php echo $values["item_id"]; ?>"><span class="text-danger">Eliminar</span></a></td>
</tr>
<?php
$total = $total + ($values["item_quantity"] * $values["item_price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<td align="right">$ <?php echo number_format($total, 2); ?></td>
<td></td>
</tr>
<?php
}
?></table>
</div>
</div>
</body>
</html> 

2 comentarios

Deja una respuesta

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Salir /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Salir /  Cambiar )

Conectando a %s