How to add more products?

7

I'm creating a personal "sales" system for my father's company. I just have a problem. I can only sell one product at a time, I'm new to PHP so its not much to do.

I want to make a "cart" and can add 2 or more products. I tried 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 "continue shopping," redoing a purchase replaces the previous purchase.

And if it's not too uncomfortable, I'd like you to point to some book or website where I can learn more about PHP.

    
asked by anonymous 26.03.2017 / 22:21

3 answers

3
  

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

For illustration, I'll use a% multidimensional% for the database turn, and the respective articles in it. But first, let's start a session, and create an immutable variable (in the sense of resisting refeshes ):

session_start();

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

And then% w / w of 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
    )
);

Next, you'll need to list them the way you want, but you'll have to define a method of capture array or array , of course for GET you'd use ajax in order to be able to dynamize the process, in this case I will use POST to construct a POST containing the GET of the product and the action .

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

If you have the products, the list of products, variable that will keep them, now only the basket is missing, 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 can add the items to 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 for example.
$produtos = array();
$stmt =  $link->query("SELECT * FROM produtos");
while($linha = $stmt->fetch_assoc()){
    array_push($produtos, $linha);
}
  

I recommend that you read this tutorial here, you can better see how to manipulate data in loops in>, and how to make connections to the database.   You can still see the full code here at pastebin .

    
26.03.2017 / 23:31
5

There are several redundancies in your code, you use array adding the values of the session unnecessarily, but let's get right to the point, you have to simplify.

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

  

And if it's not too uncomfortable, I'd like you to point to some book or website where I can learn more about PHP.

I'm not going to index books or things like this because this is not the focus of the site, but I'll point out the PHP documentation:

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 you can do in foreach like this:

$qtdCarrinho = 0;

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

var_dump($qtdCarrinho);
    
26.03.2017 / 22:53
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 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, structure and nomenclature is a matter of opinion. The important thing is to set up a multidimensional array to be able to organize better, and you do not need to have a specific quantity-only index: $_SESSION['quantidade'] , so when you need more indexes everything will be too spread out.

The example above is the least you can do. It does not mean that you should keep the exact structure indicated. Tailor as needed to your project.

Some comments on the example:

  • 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
    );
    

    Between cart and items , I added [20] . This indicates the store ID. In case it is ID 20, for example.

  • Changing languages through the user interface
    When the site has the option to change the language, cart items must accompany. If the user is browsing English and adding products, the session will save the title in English. When switching to another language, Portuguese for example, all the interface will be in Portuguese, however, the names of the products in the cart will be in English. In this case, you should display the product name according to the language chosen by the user. This involves opinion, that is, it can be done in several ways.
    This can be bypassed in a more practical way by searching for the product name in the database than keeping it stored in session. On the other hand, saving in session optimizes performance. Think of an intelligent schema that binds both resources.

  • Change in sales value.
    The final value must be the initial value. Example, if the user added the product to the cart for the price of 50 reais, that value can not be changed at the time it is checked out (the checkout process). Something that happens in many virtual store systems is that the cart session only has the product ID. Whenever you need to list the cart items, a read is done in the database. No problem in that. The problem is when the value of the product is modified during that half time.
    This is like you are in a supermarket, get a product on the shelf for 50 reais, it arrives in the box and you have to pay 60 reais because the store system has changed the price as you walked the place.
    In many countries, and if I am not mistaken, in Brazil, this is illegal for violating consumer law (misleading advertising). For the customer has the right to pay for the price he took from the shelf. Except in very extreme cases as a really erroneous price, very out of the ordinary. There goes from the good sense and honesty of the client as well.

  • 26.03.2017 / 22:53