Shopping cart with PHP and MySQL that adds repeated products

1

I am making a shopping cart with PHP and MySQL and if you add products, but the problem is that you add the same one over and over again, even if you add a different one, always insert the same one. Even when I refresh the page, it automatically adds it. Here is a part of the code ...

<!DOCTYPE html>
<div class="columnader">
<?php
session_start();
$servidor="localhost";
    $usuario="root";
    $pass="";
    $based="pruebastarento";
    $conser=mysqli_connect($servidor, $usuario, $pass);
    $conbd=mysqli_select_db($conser,$based) or die (mysqli_error())

    $por_pagina = 6;
    if (isset($_GET['pagina'])) {
        # code...
        $pagina = $_GET['pagina'];
    }else{
        $pagina = 1;
    }

    # La pagina inicia en 0 y se multiplica por $por_pagina
    $empieza = ($pagina-1) * $por_pagina;
    # Seleccionar los registros de la tabla usuarios con LIMIT

    $query="SELECT * FROM  'tornillos' LIMIT $empieza, $por_pagina";
    $run=mysqli_query($conser,$query);

    echo"<table id='tlista' style=padding-bottom:5%;>";
    while($fila = mysqli_fetch_assoc($run))
    {
        $vars1=$fila['ID_TOR'];
        $vars2=$fila['NOM_TOR'];
        $vars3=$fila['PRECIO_TOR'];
        echo"<div style='width:300px;height:auto;'>";
        echo"ID del producto: ".$vars1."" ;
        echo "<hr>";
        echo"<center><h1 style=font-size:20px;>".$vars2."</h1></center>";
        echo"<img src='imagenes/catalogo/".$fila['FOTO_TOR']."' 
        style='height:60px;width:50%;' alt='Image Not Available'>";
        echo"<p>".$fila['DESC_TOR']."</p><br>";
        echo "<hr>";
        echo"<h2>USD$ ".$vars3."</h2>";
        echo "<hr>";
        echo "<button class='buttoncarrito' 
        onclick='javascript:InsertarCarrito();'><h4 style='text-
        align:center;'>Add to cart</h4></button>";
        echo"</div>";
    };
    echo"</table>";
    ?>

    <script type="text/javascript">
    function InsertarCarrito()
    {
        <?php
        # code...
        $request = "INSERT INTO carrito                         
        (ID_PROCAR,NOMBRE_PROCAR,CANT_PROCAR,PRECIO_PROCAR,CLIENTE_PROCAR) 
        VALUES('".$vars1."','".$vars2."','1','". 
        $vars3."','".$_SESSION['login_user']."')";
        mysqli_query($conser, $request);
        #$listo=mysqli_query($conser,$insert);#

        if (true) {echo "alert('Add to cart');";}
        else{echo "alert('Not add to cart);";}
        $vars1="";
        $vars2="";
        $vars3="";
        ?>

    }
    </script>

I also leave some images where you can see that it continues adding the same ...

And now the cart ...

    
asked by Gabriel Rodriguez Jr 29.06.2017 в 19:32
source

3 answers

1

I'll give you a basic example of how to make a cart by storing it in a database.

The first thing would be to create the basic tables, in this case for the example I will use 3 as basic as possible, customers, products and carts .

We created the shopping cart

database
-- -----------------------------------------------------
-- Schema carrito
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS 'carrito' DEFAULT CHARACTER SET utf8 ;
USE 'carrito' ;

-- -----------------------------------------------------
-- Table 'carrito'.'productos'
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS 'carrito'.'productos' (
  'idProducto' INT UNSIGNED NOT NULL AUTO_INCREMENT,
  'nombre' VARCHAR(45) NOT NULL,
  'descripcion' VARCHAR(45) NULL,
  'precio' DECIMAL(10,2) NOT NULL,
  PRIMARY KEY ('idProducto'))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table 'carrito'.'carritos'
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS 'carrito'.'carritos' (
  'idCarrito' INT UNSIGNED NOT NULL AUTO_INCREMENT,
  'idCliente' INT UNSIGNED NOT NULL,
  'idProducto' INT NOT NULL,
  'cantidad' INT NOT NULL,
  PRIMARY KEY ('idCarrito'))
ENGINE = InnoDB;

-- -----------------------------------------------------
-- Table 'carrito'.'clientes'
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS 'carrito'.'clientes' (
  'idCliente' INT UNSIGNED NOT NULL AUTO_INCREMENT,
  'nombre' VARCHAR(45) NULL,
  PRIMARY KEY ('idCliente'))
ENGINE = InnoDB;

We create a basic class for the connection

class Conexion
{
    private $servidor ="localhost";
    private $usuario ="carrito";
    private $contrasena ="carrito";
    private $nombre_bd ="carrito";
    public $link;

    public function __construct()
    {
        $this->link = new mysqli($this->servidor, $this->usuario, $this->contrasena, $this->nombre_bd) or die("Error con la base de datos.");
    }
}

We create our basic cart class and extend the connection class, explained in the comments of the class that does each thing.

class CarritoController extends Conexion
{
    // Creamos 2 variables una para armacenar el carrito y otra para guardar el id cliente 
    public $carrito = array();
    private $idCliente = null;

    public function __construct($idCliente)
    {
        /* Inicializamos la conexion a la base de datos */
        parent::__construct();
        /* Establecemos el cliente */
        $this->idCliente = $idCliente;
        /* recuperamos el estado del carrito */
        $this->show();
    }

    /* recupera y retorna el carrito de la base de datos */
    public function show()
    {
        /* Recuperar el carrito */
        $sql = 'SELECT idCarrito, idProducto, idCliente, cantidad FROM carritos WHERE idCliente = ?';
        $stmt = $this->link->prepare($sql);
        $stmt->bind_param('i', $this->idCliente);
        $stmt->execute();

        $resultado = $stmt->get_result();
        // Reseteamos el carrito antes de actualizarlo, por si acaso tiene valores de antes.
        $this->carrito = array();
        // Almacenamos el carrito en nuestra variable 
        while ($row = $resultado->fetch_assoc()) {
            $this->carrito[$row['idProducto']] = $row['cantidad'];
        }

        // Liberamos resultados
        $resultado->free_result();

        // Devolvemos el carrito
        return $this->carrito;
    }

    /* Inserta y establece la cantidad de un producto */
    public function insert($idProducto,  $cantidad=1)
    {
        // Comprobamos si existe el producto en el carrito
        if(array_key_exists($idProducto, $this->carrito))
        {
            // si existe actualizamos sumando la cantidad
            $sql = 'UPDATE carritos SET cantidad = cantidad + ? WHERE idProducto = ? AND idCliente = ? ';
        }
        else
        {
            // si no existe insertamos
            $sql = 'INSERT INTO carritos (cantidad, idProducto, idCliente) VALUES (?, ?, ?)';
        }

        $stmt = $this->link->prepare($sql);
        $stmt->bind_param('iii', $cantidad, $idProducto, $this->idCliente);
        $stmt->execute();

        // recuperamos el estado del carrito despues de los cambios
        $this->show();

        return true;
    }

    /* Elimina un producto del carrito */
    public function delete($idProducto)
    {           
        // Comprobamos si existe el producto en el carrito
        if(array_key_exists($idProducto, $this->carrito))
        {
            // si existe eliminamos el producto
            $sql = 'DELETE FROM carritos WHERE idProducto = ? AND idCliente = ? ';
            $stmt = $this->link->prepare($sql);
            $stmt->bind_param('ii', $idProducto, $this->idCliente);
            $stmt->execute();

            // recuperamos el estado del carrito despues de los cambios
            $this->show();

            return true;
        }

        return false;
    }

    /* Descarta todo el carrito */
    public function destroy()
    {
        $sql = 'DELETE FROM carritos WHERE idCliente = ? ';
        $stmt = $this->link->prepare($sql);
        $stmt->bind_param('i', $this->idCliente);
        $stmt->execute();

        // recuperamos el estado del carrito despues de los cambios
        $this->show();

        return true;
    }

    /* Elimina los artuculos que tencgan cantidad menor a 1 y cierra la conexion*/
    public function __destruct()
    {
        $sql = 'DELETE FROM carritos WHERE idCliente = ? AND cantidad < 1';
        $stmt = $this->link->prepare($sql);
        $stmt->bind_param('i', $this->idCliente);
        $stmt->execute();
        $stmt->close();
    }
}

How to use it

// Inicializamos el objeto con el idCliente
$carrito = new CarritoController(1);

// insertar un producto, pasando el idProducto y la cantidad
$carrito->insert(3, 5);

// Restar cantidad a un producto, pasamos idProducto y cantidad en negativo
$carrito->insert(3, -2);

// Eliminar un producto del carrito, pasamos el idProducto
$carrito->insert(3);

// Retornar el estado del carrito
$articulos = $carrito->show();

// Vaciar o eliminar el carrito
$carrito->destroy();

Obviously this code is quite improved but I hope you get a basic idea of how to do it.

    
answered by 08.07.2017 в 23:38
0

The problem you have is that when you paint the page, the InsertCarrito function will be in the HTML painted with the INSERT with the variables $ vars1, $ vars2, etc. replaced by the last value they had when making the loop earlier in the code.

This is because you can not use PHP code inside JavaScript assuming it's going to be dynamic.

The correct way to do what you want to do is to use AJAX calls to a PHP if you want to use JavaScript, or you can not use JS at all by rethinking the code in the following way, which would be the simplest:

Forget the InsertCarrito function, and paint the button to add the product to the cart as follows:

echo "<a href='?accion=insertar&id=".$vars1."&nombre=".$vars2."&precio=".$vars3."&pagina=".$pagina."'><button class='buttoncarrito'><h4 style='text-align:center;'>Add to cart</h4></button>";

In this way, each product will have a link that will pass back to the PHP script the id, name and price to insert, and the current page in which we are to not lose it.

Above all, right after declaring $ condb:

$conbd=mysqli_select_db($conser,$based) or die (mysqli_error())

if (isset($_GET['accion']) && $_GET['accion'] == "insertar") {
    $request = "INSERT INTO carrito                         
    (ID_PROCAR,NOMBRE_PROCAR,CANT_PROCAR,PRECIO_PROCAR,CLIENTE_PROCAR) 
    VALUES('".$_GET['id']."','".$_GET['nombre']."','1','". 
    $_GET['precio']."','".$_SESSION['login_user']."')";
    mysqli_query($conser, $request);
    echo "<script>alert('Add to cart');</script>";
}

In this way, if the PHP script arrives by GET the action variable, and this is equal to "insert", we act accordingly (That is, we insert the values that have also reached us by GET in the database, and we show an alert by javascript.

    
answered by 22.12.2017 в 14:27
0

you are inserting the records because in the foreground PHP is executed with the insert that is included in this javascript function, what you must do is use AJAX to send the data and register them with a request

Example you create your file

  

addProduct.php

<?php
session_start();
$servidor="localhost";
$usuario="root";
$pass="";
$based="pruebastarento";
$conser=mysqli_connect($servidor, $usuario, $pass);
$conbd=mysqli_select_db($conser,$based) or die (mysqli_error());
$vars1 = $_POST['ID_PROCAR'];
$vars2 =$_POST['NOMBRE_PROCAR'];
$vars3 = $_POST['PRECIO_PROCAR'];
$request = "INSERT INTO carrito(ID_PROCAR,NOMBRE_PROCAR,CANT_PROCAR,PRECIO_PROCAR,CLIENTE_PROCAR) VALUES('".$vars1."','".$vars2."','1','".$vars3."','".$_SESSION['login_user']."')";
mysqli_query($conser, $request);
?>

and in your javascript:

function InsertarCarrito(id, name, price) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("POST", "agregarProducto.php", true);
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("ID_PROCAR="+id+"&NOMBRE_PROCAR="+name+"&PRECIO_PROCAR="+price);
}

modify the add button by:

echo "<button class='buttoncarrito' onclick='javascript:InsertarCarrito('".$vars1."', '".$vars2."', '".$vars3."');'><h4 style='text-align:center;'>Add to cart</h4></button>";
    
answered by 22.12.2017 в 15:37