Save array values in Database

Asked

Viewed 69 times

0

I have a shopping cart:

<?php

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

          // ADD ITEMS TO CART //
          if(isset($_GET['add']) && $_GET['add'] == "carrinho") {
            $idProduto = $_GET['id'];
            if(!isset($_SESSION['itens'][$idProduto])) {
              $_SESSION['itens'][$idProduto] = 1;
            } else {
              $_SESSION['itens'][$idProduto] += 1;
            }
          }
          
          // REMOVE ITEMS FROM CART //
          if(isset($_GET['removeone']) && $_GET['removeone'] == "carrinho") {
            $idProduto = $_GET['id'];
            if(!isset($_SESSION['itens'][$idProduto])) {
              $_SESSION['itens'][$idProduto] = 1;
            } else {
              $_SESSION['itens'][$idProduto] -= 1;
            }
          }

          // SHOW PRODUCTS //
          if (count($_SESSION['itens']) == 0) {
            echo '<h5>Seu carrinho está vazio. <a href="index.php">Clique aqui para adicionar itens!</a></h5>';
          }

          else {
            $conexao = new PDO('mysql:host=***;dbname=***',"***","***");

            foreach($_SESSION['itens'] as $idProduto => $quantidade) {
              $select = $conexao->prepare("SELECT * FROM produtos WHERE id=?");
              $select->bindParam(1,$idProduto);
              $select->execute();
              $produtos = $select->fetchAll();
              $total = $quantidade * $produtos[0]["valor"];
              $totalgeral += $total;

        ?>

And this shows the products in a table:

<?php

          echo
            '<td>'.$produtos[0]["nome"].'</td>
            <td>R$ '.number_format($produtos[0]["valor"],2,",",".").'</td>
            <td>'.$quantidade.'</td>
            <td>R$ '.number_format($total,2,",",".").'</td>
            <td>
                <a href="carrinho.php?add=carrinho&id='.$idProduto.'"><i class="fa fa-plus"></i></a> &nbsp;&nbsp;
                <a href="carrinho.php?removeone=carrinho&id='.$idProduto.'"><i class="fa fa-minus"></i></a> &nbsp;&nbsp;
                <a href="remover.php?remover=carrinho&id='.$idProduto.'"><i class="fa fa-trash"></i></a>
            </td>
            ';

          }
        }

      ?>

Send via POST with some other fields I need to add to the bank. Save it inside a input="hidden":

<input type="hidden" name="produtos" value="<?php echo $produtos; ?>" required>

I want to take it in the other file, to send it to the bank, I do it this way:

$produtos = $_POST['produtos'];
  $produtos = array();
  foreach($_POST as $nome => $quantidade) {
    
    echo $produtos;
    
  } 

When I try to "catch" him in the other file, I just get: "ArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArray"

I can’t figure out what I’m missing. Can you help me?

EDIT: I put the brackets in the input:

<input type="hidden" name="produtos[]" value="<?php echo $produtos; ?>" required>

And I tried to get the values in a different way:

$produtos = $_POST['produtos'];
  $produtos = '"' . implode('","', $produtos) . '"';
  
  echo $produtos;

Even so, without success.

EDIT 2:

Another way, also unsuccessful. I only get the word Array:

$contador = count($_POST["produtos"]);
  for ($x = 0; $x < $contador; $x++){
  $produto = $_POST["produtos"][$x];
  
    echo $produto;
    
  }

I can’t see the solution!

EDIT 3: Sorry, I’m desperate for the solution...

What I’m realizing is that the values are not being passed correctly from one file to another, because Gero an array in carrinho2.php and I can see the values with the echo.

Does the problem lie in the input?

<form action="carrinho2.php" method="post" id="form_payment">

            <p class="title_bold">Valor total dos produtos: R$ <?=number_format($totalgeral,2,",",".")?></p>
            <p class="title_bold">Frete escolhido: <input type="text" name="freteescolhido" id="freteescolhido" readonly required /> </p>
            <p class="title_bold">Valor total do pedido: R$ <input type="text" name="valorfinalcomofrete" id="valorfinalcomofrete" readonly required /></p>

            <!-- PRODUCT DETAILS -->
            <input type="hidden" name="altura" value="<?php echo $altura; ?>" required>
            <input type="hidden" name="largura" value="<?php echo $largura; ?>" required>
            <input type="hidden" name="comprimento" value="<?php echo $comprimento; ?>" required>
            <input type="hidden" name="peso" value="<?php echo $peso; ?>" required>
            <input type="hidden" name="produtos[]" value="<?php echo $produtos; ?>" required>
            
            <!-- CUSTOMER DATA -->
            <input type="hidden" name="nome" value="<?php echo $razaosocial; ?>" required>
            <input type="hidden" name="cnpj" value="<?php echo $cnpj; ?>" required>
            <input type="hidden" name="endereco" value="<?php echo $endereco; ?>" required>
            <input type="hidden" name="bairro" value="<?php echo $bairro; ?>" required>
            <input type="hidden" name="cidade" value="<?php echo $cidade; ?>" required>
            <input type="hidden" name="estado" value="<?php echo $estado; ?>" required>
            <input type="hidden" name="cep" value="<?php echo $cep; ?>" required>

            <!-- ORDER DATA -->
            <input type="hidden" name="datavencimento" value="<?php echo $hoje; ?>" required>

            <!-- ORDER BUTTON -->
            <button type="submit" class="btn btn-dhfarma">Finalizar Pedido</button>

          </form>
  • Can you describe in text what this last piece of code should do? Why define the variable $produtos twice? Why the loop iterates the superglobal variable $_POST?

  • It is to take the variable data and try to show... showing, I saved in the database... But you already found an error. Any suggestion, please?

  • I tried to use the for also, but I have not had satisfactory results.

1 answer

1

By making echo of a array in php it will present you a 'friendly' format, and so your backend and frontend interconnection will not be the best... there are some structuring languages out there as kind JSON :)

Instead:

<input type="hidden" name="produtos[]" value="<?php echo $produtos; ?>" required>

Try turning dandos into JSON example:

<input type="hidden" name="produtos[]" value="<?= json_encode($produtos); ?>" required>

Then in your backend you’ll decode (transform JSON into PHP array or object), example:

  $produtos = json_decode($_POST['produtos']);
  foreach($produtos as $produto) {
    
    echo $produto;
    
  } 

It is of note that yours was with errors, the cycle should consist of the products obtained by the post.

  • 1

    Grateful for the support, my friend. I have an eternal fight with the arrays, something so simple that I get sometimes. It is more because of despair and delay. Thank you from my heart for the support! I will test and return with the answer. Great hug!

  • Thank you, I hope I helped! : ) (don’t forget later to mark the answer that you consider correct and that helped you)

  • 1

    No doubt, once resolved, I will mark it. I know how important it is for the community! Hugging!

Browser other questions tagged

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