How to add more products?

Asked

Viewed 1,974 times

7

I’m creating a personal "sales" system for my father’s company. I’m just having a problem. I can only sell one product at a time, I’m new to PHP so it doesn’t have much to do.

I want to make a "cart" and can add 2 or more products. I tried to do the following:

session_start();
include("includes/conexa.php");
include("includes/topo.php");

$busca = $_POST['produto'];
    $_SESSION['produto'] = $busca;
$qnts = $_POST['quantidade'];
    $_SESSION['quantidade'] = $qnts;


    $produto1 = array($_SESSION['produto']);
    $qnts1 = array($_SESSION['quantidade']);
    var_dump($produto1);
    var_dump($qnts1);

    $produto2 = array($_SESSION['produto2']);
    $qnts2 = array($_SESSION['quantidade2']);
    var_dump($produto2);
    var_dump($qnts2);

    

Continuar Comprando

And if I click on "continue buying", redo a purchase it replaces the previous purchase.

And if it’s not too much trouble, I’d like you to recommend some book or website where I can learn more about PHP.

3 answers

5

There are several redundancies in your code, you use array adding session values without need, but let’s get to the point, has how to simplify.

session item can receive arrays normally, working with arrays will be easier.

And if it’s not too much trouble, I’d like you to recommend some book or website where I can learn more about PHP.

I will not indict books or things like that because this is not the focus of the site, but I point out the documentation of PHP:

An example shopping cart with simple array would look like this:

session_start();

//Cria o carrinho se não existir
if (!isset($_SESSION['carrinho'])) {
   $_SESSION['carrinho'] = array();
}

$carrinho = $_SESSION['carrinho'];

//Verifica se as variáveis vieram via POST, se for adiciona um novo item ao carrinho
//NOTA: Recomendo validar essas variáveis, verificando se existem no banco ao invés de trazer tudo via post
if (isset($_POST['produto'], $_POST['quantidade'])) {
     //Adiciona ao array, note que [] equivale ao array_push()
     $carrinho[] = array(
         'produto' => $_POST['produto'],
         'quantidade' => (int) $_POST['quantidade']
     );
}

//Salva na sessão
$_SESSION['carrinho'] = $carrinho;

//Exibe produtos
foreach ($carrinho as $item) {
     var_dump($item['produto'], $item['quantidade']);
}

And if you want to add the total amount of products independent of the product can do in foreach so:

$qtdCarrinho = 0;

//Exibe produtos
foreach ($carrinho as $item) {
     var_dump($item['produto'], $item['quantidade']);
     $qtdCarrinho += $item['quantidade'];
}

var_dump($qtdCarrinho);
  • 1

    @Miguel is right (I think it refers to if and not foreach), corrected =)

  • ha, yes yes it was to if clear. Good cart

  • What if I want to cancel the inserted products ? I can create a stop button on Session ?

  • @Andrejunior to remove all just put on the removal page this $_SESSION['carrinho'] = array();, or when you complete the purchase, you will set an empty variable again

3


For security reasons, I recommend using a Framework own to create virtual stores, because they offer greater security, create stores in this way, is usually for people who already have knowledge in the area, and are familiar with security measures, and programming standards, or even for those who simply want to understand the dynamics of a virtual store.

For illustration, I will use a array multidimensional for the database’s turn, and the respective articles in it. But first, let’s start a session, and create an immutable variable (in order to resist refeshes):

session_start();

if(!isset($_SESSION['cesto'])){
    $_SESSION['cesto'] = array();
}

And then the array with the products that will be used in the example:

// produtos
$produtos = array(
    array(
        'id' => 1,
        'nome' => 'Lapis',
        'preco' => 50
    ),
    array(
        'id' => 2,
        'nome' => 'Marcador',
        'preco' => 20
    ),
    array(
        'id' => 3,
        'nome' => 'Borracha',
        'preco' => 10
    ),
    array(
        'id' => 4,
        'nome' => 'Mochila',
        'preco' => 200
    )
);

Then you’ll need to list them any way you want, but you’ll have to define a capture method GET or POST, of course for the POST you’d have to use ajax in order to streamline the process, in this case I will use GET to build a querystring containing the id of the product and the action desired.

// listar produtos
foreach($produtos as $produto){
    print "<p>{$produto['nome']} ({$produto['preco']}) - <a href=\"?produto={$produto['id']}&a=adicionar\">adicionar</a></p>";
}

Already if you have the products, the listing of the products, variable that will keep them, now just missing the basket, let’s see:

// cesto
if(!empty($_SESSION['cesto'])){
    $total = 0;
    print "<strong>cesto (" . count($_SESSION['cesto']) . ")</strong><br>";
    foreach($_SESSION['cesto'] as $item => $detalhes){
        print $detalhes['nome'] . " x " . $detalhes['quantidade'] . "<br>";
        $total += $detalhes['quantidade'] * $detalhes['preco'];
    }
    print "<strong>total: </strong>" . number_format($total, 2);
} else {
    print "<strong>cesto vazio</strong>";
}

Now, to make the basket work, so we’re able to add the items into it:

// adicionar itens ao carrinho
if(isset($_GET['produto']) && isset($_GET['a'])){
    if($_GET['a'] == 'adicionar'){
        if(!empty($_SESSION['cesto'])){
            foreach($_SESSION['cesto'] as $item => $produto){
                if($item == $_GET['produto']){
                    $_SESSION['cesto'][$item]['quantidade'] = $produto['quantidade'] + 1;
                    break;
                } else {
                    foreach($produtos as $produto){
                        if($produto['id'] == $_GET['produto']){
                            $_SESSION['cesto'][$produto['id']] = ['nome'=>$produto['nome'], 'preco'=>$produto['preco'], 'quantidade'=>1];
                            break;
                        }
                    }
                }
            }
        } else {
            foreach($produtos as $produto){
                if($produto['id'] == $_GET['produto']){
                    $_SESSION['cesto'][$produto['id']] = ['nome'=>$produto['nome'], 'preco'=>$produto['preco'], 'quantidade'=>1];
                }
            }
        }
    }
}


EDIT : To return the products through the database, you can do this way for example.

$produtos = array();
$stmt =  $link->query("SELECT * FROM produtos");
while($linha = $stmt->fetch_assoc()){
    array_push($produtos, $linha);
}

I recommend you read this tutorial here, there you can see better how to manipulate data in loops, and how to make connections with the database. You can also see the full code here on Pastebin.

  • I have a problem.... You know, when listing products. I did the following : <pre>if(!isset($_SESSION['basket']){ $_SESSION['basket'] = array(); } // products $query = $PDO->query("SELECT * FROM products"); while($line = $query ->fetch(PDO::FETCH_ASSOC)) ģ header('Content-Type: text/html; charset=utf-8'); $id = "{$line['id']}"; $name = "{$line['name']}"; $price = "{$line['price']}"; $products = array( array( 'id' => $id, 'name' => $name, 'price' => $price ), ); }</pre> Only it shows only one product.

  • $produtos = array( array( 'id' => $id, 'nome' => $nome, 'preco' => $preco ), ) trade this for array_push($produtos, $linha), but rather declares $produtos = array() outside the while.

2

Define a multidimensional array:

$_SESSION['cart']['items'] = array(
    'id' => 5, // código do produto
    'title' => 'produto teste', // título/nome do produto
    'selling_price' => 10.00 // preço de venda
    'quantity' => 5 // quantiadde
);

Following the original code of your question, it could be something like this

$_SESSION['produto'][10] = array(
    'nome' => 'produto teste',
    'preço' => 10.00,
    'quantidade' => 5
);

The [10] is the product id.

Finally, the structure and nomenclature is a matter of opinion. The important thing is to assemble a multidimensional array in order to organize it better and you don’t need to have a specific quantity-only index: $_SESSION['quantidade'] because that way, when you need more indexes will be very dispersed.

The example above is the least that can be done. It does not mean that you should keep the exact structure indicated. Adapt according to the need of your project.

Some comments on the example:

  1. Does not support multiple stores.
    To support multiple stores, for example, a virtual mall with different stores, you must add one more level to the array:
$_SESSION['cart'][20]['items'] = array(
  'id' => 5, // código do produto
  'title' => 'produto teste', // título/nome do produto
  'selling_price' => 10.00 // preço de venda
  'quantity' => 5 // quantiadde
);

Amid cart and items, added [20]. This indicates which store ID. In case it is ID 20, for example.

  1. Language exchange via user interface
    When the site has an option to change the language, the cart items must follow. If the user is browsing in English and adding products, Session will keep the title in English. When changing to another language, Portuguese for example, the whole interface will be in Portuguese, however, the product names in the cart will be in English. In this case, it must display the product name according to the language chosen by the user. This involves a matter of opinion, that is, it can be done in several ways.
    This can be circumvented more practically by searching for the product name in the database than by keeping it stored in Sesssion. On the other hand, saving in Session optimizes performance. Think of a clever scheme that brings together both features.

  2. Change in sale value.
    The final value shall be the initial value. Example, if the user added the product in the cart for the price of 50 reais, this value can not be changed at the time of checkout (checkout process). Something that happens in many virtual shop systems is the cart session owning only the product ID. Whenever you need to list the items in the cart, a reading is done in the database. No problem there. The problem is when the product value is modified during that time.
    That’s like being in a supermarket, picking up a product on the shelf for 50 reais, arriving at the cashier and having to pay 60 reais because the store system changed the price while you walked around the place.
    In many countries, and if I’m not mistaken, in Brazil, this is illegal for violating consumer law (misleading advertising). Because the customer has the right to pay the price he took off the shelf. Except in very extreme cases as a really wrong price, very out of the ordinary. There goes customer’s common sense and honesty too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.