Featured Post

Tablas Responsivas con Bootstrap 5 pc escritorio y dispositivos mobiles

CARRITO COMPRAS EN 2 WEB CON SESSION PHP MYSQL

index.php

<!DOCTYPE html>

<html lang="es">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Document</title>


<style>


* {

font-family: Century Gothic;

font-size: 16px;

margin: 0 auto;

padding: 0px 15px 0px 15px;

}


table {

  border-collapse: collapse;

  width: 100%;

  border-radius: 8px;

  box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);

}


table td, table th {

  border: 1px solid #ddd;

  padding: 8px;

}


table tr:nth-child(even){background-color: #f2f2f2;}


table tr:hover {background-color: #ddd;}


table th {

  padding-top: 5px;

  padding-bottom: 5px;

  text-align: left;

  background-color: #111;

  color: white;

  border-radius: 2px;

  box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);



@media only screen and (max-width: 600px) {



* {

font-size: 13px;

font-weight: bold;

}


#buscar #rub{

padding: 5px 5px;

}



}



#card {

  border: 1px solid grey;

 padding: 5px 5px;

 margin: 5px;

border-radius: 8px;

}


@media only screen and (max-width: 600px) {



* {

  font-size: 13px;

  font-weight: bold;

}




input  {

  background: aqua;

  width: 200px;

  padding: 5px 5px;

}


#rub {

 padding: 7px 7px;

  width: 170px;

}



button[type='submit'] {

   padding: 5px 5px;

  width: 80px;

}


input[type='submit'] {

   padding: 5px 5px;

  width: 130px;

}


}



</style>



</head>

<body>


<?php

// Iniciamos la sesión

session_start();


// Conexión a la base de datos

$servername = "localhost";

$username = "root";

$password = "root";

$dbname = "carrito_compras";


$conn = new mysqli($servername, $username, $password, $dbname);


if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}


// Obtenemos los productos de la base de datos

$sql = "SELECT * FROM productos";

$result = $conn->query($sql);


if($result->num_rows > 0) {

    // Mostramos la lista de productos

    echo '<h2>Lista de Productos</h2>';

    echo '<table>';

    echo '<tr><th>id</th><th>Nombre</th><th>Precio</th><th>Cantidad</th></tr>';

    

    while($row = $result->fetch_assoc()) {

        echo '<tr>';

        echo '<td>'.$row['id'].'</td>';

        echo '<td>'.$row['nombre'].'</td>';

        echo '<td>$'.$row['precio'].'</td>';

       

        

        // Formulario para agregar un producto al carrito

        echo '<td>

                <form method="post" action="carrito.php">

                    <input type="number" name="product_qty" value="1" min="1" max="1000" required>

                    <input type="hidden" name="product_id" value="'.$row['id'].'" required>

                    <input type="submit" name="add_to_cart" value="Agregar">

                </form>

            </td>';

        

        echo '</tr>';

    }

    

    echo '</table>';

} else {

    echo "<p>No hay productos disponibles.</p>";

}


// Cerramos la conexión a la base de datos

$conn->close();

?>


</body>

</html>


/////////////////////

carrito.php


<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

<style>

* {
font-family: Century Gothic;
font-size: 16px;
margin: 0 auto;

}

table {
  border-collapse: collapse;
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);
}

table td, table th {
  border: 1px solid #ddd;
  padding: 8px;
}

table tr:nth-child(even){background-color: #f2f2f2;}

table tr:hover {background-color: #ddd;}

table th {
  padding-top: 5px;
  padding-bottom: 5px;
  text-align: left;
  background-color: #111;
  color: white;
  border-radius: 2px;
  box-shadow: 0 8px 16px 0 rgba(0,0,0,0.2), 0 6px 20px 0 rgba(0,0,0,0.19);



@media only screen and (max-width: 600px) {

* {
font-size: 13px;
font-weight: bold;
margin: 0 auto;
padding: 0px 15px 0px 15px;
}

#buscar #rub{
padding: 5px 5px;
}


}


#card {
border: 1px solid grey;
padding: 5px 5px;
margin: 5px;
border-radius: 8px;
}


@media only screen and (max-width: 600px) {

* {
  font-size: 13px;
  font-weight: bold;
}

input  {
  background: aqua;
  width: 200px;
  padding: 5px 5px;
}

#rub {
 padding: 7px 7px;
  width: 170px;
}


button[type='submit'] {
   padding: 5px 5px;
  width: 80px;
}

input[type='submit'] {
   padding: 5px 5px;
  width: 130px;
}

}


</style>


</head>
<body>
  

<?php

// Iniciamos la sesión
session_start();

// Conexión a la base de datos
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "carrito_compras";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Verificamos si se ha añadido un producto al carrito
if(isset($_POST['add_to_cart'])) {
   
    $product_id = $_POST['product_id'];
    $product_qty = $_POST['product_qty'];
     
// Verificamos si el producto ya está en el carrito
    if(isset($_SESSION['cart'][$product_id])) {

    $_SESSION['cart'][$product_id]['cantidad'] += $product_qty;

    } else {

 // Obtenemos la información del producto de la base de datos
    $sql = "SELECT * FROM productos WHERE id = $product_id";
    $result = $conn->query($sql);
    $row = $result->fetch_assoc();
    
    // Añadimos el producto al carrito
    $_SESSION['cart'][$product_id]['idp'] = $row['id'];
    $_SESSION['cart'][$product_id]['nombre'] = $row['nombre'];
    $_SESSION['cart'][$product_id]['precio'] = $row['precio'];
    $_SESSION['cart'][$product_id]['cantidad'] = $product_qty;
       
    }


}

// Actualizamos la cantidad de un producto en el carrito
if(isset($_POST['update_cart'])) {

    $product_id = $_POST['product_id'];
    $product_qty = $_POST['product_qty'];
    
    $_SESSION['cart'][$product_id]['cantidad'] = $product_qty;
}

// Eliminamos un producto del carrito
if(isset($_POST['remove_cart'])) {
    $product_id = $_POST['product_id'];
    
    unset($_SESSION['cart'][$product_id]);
}





if(isset($_POST['vaciar'])) {

// Si el carrito existe, lo vaciamos
if(isset($_SESSION['cart'])){
  $_SESSION['cart'] = array();
}

header("Location: carrito.php");
//exit();


}



///////////////////////////////////////////////////

// Mostramos los productos en el carrito

$total = 0;

if(isset($_SESSION['cart'])) {

echo "<div id='card'>";
echo "<div style='overflow-x: auto;'>";

echo "<table>";

echo "<tr><th>Indice</th><th>Id</th><th>Nombre</th><th>Cantidad</th><th>Precio</th><th>SubTotal</th><th>Accion</th></tr>";


foreach($_SESSION['cart'] as $product_id => $product) {

$subtotal = $product['precio'] * $product['cantidad'];
$total += $subtotal;



echo "<tr>";

echo "<td>".$product_id."</td>";
echo "<td>".$product['idp']."</td>";
echo "<td>".$product['nombre']."</td>";


echo "<td>
<form method='post' action=''>
<input type='number' name='product_qty' value=".$product["cantidad"]." min='1' max='1000'>
<input type='hidden' name='product_id' value=".$product_id.">

<button type='submit' name='update_cart'><i class='fa fa-refresh' style='font-size:20px;'></i></button>


</form>'
                         
</td>";


echo "<td>$".$product['precio']."</td>";


echo "<td style='text-align:center;'>$".$subtotal."</td>";



echo "<td>
<form method='post' action=''>
                <input type='hidden' name='product_id' value=".$product_id.">
               <button type='submit' name='remove_cart'><i class='fa fa-trash' style='font-size:20px;'></i></button>
            </form>

                         
</td>";



echo  "</tr>";



    }

echo "<td colspan='5'><p style='text-align:right;font-weight:bold;font-size:24px;'>Total :</p></td><th style='color:yellow;text-align:center;font-size:24px;'>$ ".$total."</th><td></td>";


echo "<tr><td colspan='7' style='text-align:right;'><form method='post' action=''>
<button  type='submit' name='vaciar'><i class='fa fa-eraser' style='font-size:20px;'></i> Vaciar Carrito</button>
</form></td></tr>";


echo "<tr><td colspan='7'>


<a href='index.php'>
    <button><i class='fa fa-reply' style='font-size:20px;'></i> Volver a Productos</button>
</a>

</td></tr>";


  echo "</table></div></div>";


} else {
    echo "<p>No hay productos en el carrito.</p>";
}



// Cerramos la conexión a la base de datos
$conn->close();

?>

</div>
</body>
</html>



Post publicado por:


Comentarios