How to store multiple values in a variable?

Asked

Viewed 10,480 times

1

I’m creating a system with several products, and in them will have a link, so:

<a href ="verificar.php?valor=20">Imagem</a>

The archive ( verificar.php ) will receive for $_GET the value of the variable ( valor ) that in the example is 20.

My question is: how to store this value in a variable, because it will have several products, and when you click on them you will have to save the value and add them at the end...

Can I use the array? It is possible to show me an example of code?

  • When do you make the ajax call? click a click or all together? or have a form which is submitted with all values?

  • From what you say, you will need to use an array in Session. You are already using Session?

  • You will have to add the values first, recommend using javascript, for only after completing the sum, can pass as parameter the total value to the verificar.php

  • Your question is unclear, if you explain better how your code works and put here an example of the HTML of a product, it will be possible to answer your question. For now it’s too vague...

  • 1

    @Pauloroberto It is a danger to add everything via JS and only pass the value to the server! If someone opens a Chrome console, they can easily make a million dollar purchase cost $1. Ideally pass the id of each product and quantities, and do the calculations on the server

  • But this is an online shopping system?!

  • @bfavaretto obviously the value would be conferred on php né guy

  • 4

    @Pauloroberto Obviously for you and for me. For the author of the question, we do not know... He needs to clarify several things so that the question can receive an accurate answer.

  • You’re right @bfavaretto

Show 4 more comments

3 answers

2

You can save the sum to Session, so every time someone clicks on the link to the page checks.php, the value of the "value" variable will be added to another "total value" variable, saved to Session.

php checks.

session_start();
$_SESSION['valor_total'] += $_GET['valor'];

echo $_SESSION['valor_total'];


PHP Func. session_start()
PHP Sessions - W3schools

  • 4

    Avoid using the reference of w3schools, http://meta.pt.stackoverflow.com/questions/692/w3schools-e-uma-referencia-horrivel-certo http://www.w3fools.com/

  • 2

    +1 Although the source is dubious, the content is correct

2

You can pass multiple values to the same variable using straight parentheses []. This makes PHP store values in an array.

<a href ="verificar.php?valor[]=20&valor[]=30">Imagem</a>

PHP will receive in $_GET['value'] the array('20', '30');

2

Well, without knowing more information it’s hard to understand what you want.

How to store multiple values in a variable?

Using an array(array) or an object.

$array = array('a', 'b', 'c'); //Array

//Objecto
$obj = new StdClass(); 
$obj->foo = 'bar';
$obj->baz = 'bazinga';

I am creating a system with several products,(...) My question is: how to store this value in a variable, because it will have several products, and when you click on them you will have to save the value and add them at the end...

It seems to be wanting to make a shopping cart.

From what it shows, if there is no javascript behind, your link will trigger a page redirection. To avoid this you have to use AJAX (Asynchronous Javascript and XML) in EN -> "Asynchronous Javascript and XML"


Code Example

A relatively simple way to make a shopping cart on a single page can be as follows:

cart php.

<?php
class Producto {
    public $id;
    public $nome;
    public $preco;
    public $quantidade = 0;

    public function __construct($id, $preco, $nome, $quantidade = 0) {
        $this->id = $id;
        $this->preco = $preco;
        $this->nome = $nome;
        $this->quantidade = $quantidade;
    }

    public function adicionar($quantidade = 1) {
        $this->quantidade = $this->quantidade + $quantidade;
    }

    public function remover($quantidade = 1) {
        $this->quantidade = $this->quantidade - $quantidade;
        if ($this->quantidade < 0)
            $this->quantidade = 0;
    }
}

class Carrinho implements IteratorAggregate {

    public $productosNoCarrinho = array();

    public function __construct ($listaDeProductos){
        $this->productosNoCarrinho = $listaDeProductos;
    }

    public function adicionar($id, $quantidade = 1) {
        if (!isset($this->productosNoCarrinho[$id]))
            return false;

        $this->productosNoCarrinho[$id]->adicionar($quantidade);
        return true;
    }

    public function remover($id, $quantidade = 1) {
        if (!isset($this->productosNoCarrinho[$id]))
            return false;

        $this->productosNoCarrinho[$id]->remover($quantidade);
        return true;
    }

    public function total() {
        $total = 0;
        foreach ($this->productosNoCarrinho as $prod) {
            $total += $prod->preco * $prod->quantidade;
        }
        return $total;
    }

    public function getIterator() {
        return new ArrayIterator($this->productosNoCarrinho);
    }

    public function mostrar() {
        $html = "<table><tr><td>#</td><td>Producto</td><td>Preco</td></tr>";
        foreach ($this->productosNoCarrinho as $producto) {
            if ($producto->quantidade > 0) {
                $html .= "<tr><td>{$producto->quantidade}</td>".
                "<td>{$producto->nome}</td>".
                "<td>".$producto->preco * $producto->quantidade."</td></tr>";
            }
        }
        $html .= "<tr><td></td><td></td><td>".$this->total()."</td></tr>";
        $html .= "</table>";
        return $html;
    }

    public function __toString() {
        return $this->mostrar();
    }
}

$listaDeProductos = array( 
    'A1' => new Producto('A1', 499, 'iPad air'),
    'A2' => new Producto('A2', 600, 'iPhone 5S'),
    'A3' => new Producto('A3', 1200, 'MacBook pro'),
    'A4' => new Producto('A4', 1100, 'iMac')
);

session_start();

if(!isset($_SESSION['carrinho'])) {
    $_SESSION['carrinho'] = new Carrinho($listaDeProductos);
}

$carrinho = $_SESSION['carrinho'];

if (isset($_GET['action'])) {
    if ($_GET['action'] == 'add' && isset($_GET['id'])) {
        $carrinho->adicionar($_GET['id']);
    } else if ($_GET['action'] == 'remove' && isset($_GET['id'])) { 
        $carrinho->remover($_GET['id']);
    }
    //print $carrinho->mostrar();
}
?>
<!DOCTYPE HTML>
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
<div id="lista-de-productos">
<h1>Productos</h1>
<ul>
    <?php foreach ($listaDeProductos as $prod) { ?>
        <li class="producto"
                data-id="<?=$prod->id?>"
                data-preco="<?=$prod->preco?>"
                data-nome="<?=$prod->nome?>"
        >
        <?=$prod->nome?> [<?=$prod->preco?>&euro;]
        <button class="adicionar">+</button>
        <button class="remover">-</button>
        </li>
    <?php } ?>
</ul>    
</div>
<hr>
<h1>Carrinho</h1>
<div id="carrinho">
<?=$carrinho?>
</div>
<script>
    $(document).ready( function() {
        var carrinhoID = $(this).attr("data-carrinhoID");

        $(document).on("click", ".producto .adicionar", function() {
            var prodID = $(this).parent().attr("data-id");
            $("#carrinho").load("carrinho.php?action=add&id=" +prodID +" #carrinho", function(responseText, textStatus, XMLHttpRequest) {
                //Sucesso
            });
        });

        $(document).on("click", ".producto .remover", function() {
            var prodID = $(this).parent().attr("data-id");
            $("#carrinho").load("carrinho.php?action=remove&id=" +prodID +" #carrinho", function(responseText, textStatus, XMLHttpRequest) {
                //Sucesso
            });
        });
    });
</script>
</body>
</html>

Explaining the code...

What this code does is create a Cart (Object of the Cart class) in the session. The control of the cart (and the price and total to pay) is done by the server but the action to add and remove is done by the client (browser) through AJAX.

Logically speaking, what happens is this:

  1. The user enters the page http://exemplo.com/carrinho.php(o Browser sends a GET request to the server)
  2. The Server receives the request and sees that, in the headers, no session cookie was passed.
  3. The Server creates a session for the user and sends a Setcookie to the headers
  4. The Browser receives and stores Cookie.
  5. User adds a product to cart
  6. The Browser sends a GET Asynchronous (AJAX) request to the server, to the same page, but with parameters in the URL ((http://exemplo.com/carrinho.php?action=add&id=XX) with the action to be performed and the product id. It also sends the cookie received from the first time the user accessed the page
  7. The Server loads the cart saved in the session, reads the order and realizes that you have to add +1 in the quantity of product XX in the cart
  8. The Server send the whole page back
  9. The Browser receives the request but instead of showing the whole page, removes only the part that is inside the div id="cart" 10 ...

The HTTP verb used is GET, but it could be POST (by the way, it made more sense). However, it is simpler to view.

WARNING: This code is for demonstration purposes only. SHALL NOT BE USED IN PRODUCTION that’s right INSECURE.

Browser other questions tagged

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