I wanted to know how to pass a record of an array from one php page to another and then to an sql table

Asked

Viewed 32 times

-1

I would like to know how to pass a record of the array of a php page to another php page that will then give an Insert in the corresponding table in the database, I am beginner in php and have tried in several ways but without success. (PS: I want to go from cart page.php to finish.php) (OBS: I also accept other suggestions on how to pass data without being by array)

My code is currently like this:

My table:

CREATE TABLE pedido (
id_pedido int not null AUTO_INCREMENT,
id_empresa int not null,
data_pedido varchar(15) not null,
data_entrega varchar(15) not null,
estado int not null,
data_vencimento varchar(45),
CONSTRAINT pk_ped PRIMARY KEY (id_pedido),
CONSTRAINT fk_ped FOREIGN KEY (id_empresa) REFERENCES empresa (id_empresa)
);

cart php.:

<?php
session_start();

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

if (isset($_GET['add']) && $_GET['add'] == 'carrinho') {

  $idProduto = $_GET['id_residuo'];
  if (!isset($_SESSION['tudo'][$idProduto])) {
    $_SESSION['tudo'][$idProduto] = 1;
  } else {
    $_SESSION['tudo'][$idProduto] += 1;
  }
}
?>

<html lang="pt-br">

<head>
  <meta charset="utf-8" />
<head>

<body>

    <table>
      <thead>
        <tr>
          <th> Nome do Residuo </th>
          <th> Quantidade </th>
          <th> Preco Unitário R$ </th>
          <th> Total </th>
          <th> Remover </th>
        </tr>
      </thead>
      <?php
      if (count($_SESSION['tudo']) == 0) {
        echo 'Carrinho Vazio';
      } else {
        try {

          $pdo = new PDO('mysql:host=localhost;dbname=bd_reuse', "root", "");
          $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $ex) {
          echo "ERRO: " . $ex->getMessage();
          exit;
        }

        $idEmpresa = $_SESSION['id_empresa'] + 0;


        $_SESSION['dados'] = array();
        $estado = "0";
        $tudo = 0;
        $quantidadeTotal = 0;

        foreach ($_SESSION['tudo'] as $idProduto => $quantidade) {

          $select = $pdo->prepare("SELECT * FROM residuo WHERE id_residuo = ?");
          $select->bindParam(1, $idProduto);
          $select->execute();
          $residuos = $select->fetchAll();
          $total = $quantidade * $residuos[0]["valor_residuo"];
          $tudo += $total;
          $valor = $residuos[0]["valor_residuo"] + 0.0;
          $quantidadeTotal += $quantidade;
          $dataP = date('d-m-Y');
          $dataE = date('d-m-Y', strtotime('+1 week'));
          $dataV = date('d-m-Y', strtotime('+1 month'));
          echo
          '<tr>
            <td>  ' . $residuos[0]["nome_residuo"] . ' </td> <br />
            <td>  ' . $quantidade . ' </td> <br />
            <td>  ' . number_format($residuos[0]["valor_residuo"], 2, ",", ".") . ' </td> <br />
            <td>  ' . number_format($total, 2, ",", ".") . ' </td> <br/>
            <td>  <a href="remover.php?remover=carrinho&id_residuo=' . $idProduto . '"> Remover </a> </td>
          </tr>';

          array_push(
            $_SESSION['dados'],
            array(
              'id_empresa' => $idEmpresa,
              'data_vencimento' => $dataV,
              'data_pedido' => $dataP,
              'data_entrega' => $dataE,
              'estado' => $estado,
              'quantidade_item' => $quantidade,
              'valor_item' => $valor
            )
          );
        }
      ?>
        <tr>
          <th colspan="5"> <?php echo '<a href="finalizar.php"> Finalizar Pedido </a>' ?> </th>
        </tr>
        <tr>
          <th colspan="3"> Valor Total </th>
          <td colspan="2"> <?php echo number_format($tudo, 2, ",", ".") ?> </td>
        </tr>
        <tr>
          <th colspan="3"> Quantidade Total </th>
          <td colspan="2"> <?php echo $quantidadeTotal ?> </td>
        </tr>
      <?php
      }
      ?>

    </table>

</body>

</html>

finish.php:

<?php
session_start();

try {
    $pdo = new PDO('mysql:host=localhost;dbname=bd_reuse', "root", "");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $ex) {
    echo "ERRO: " . $ex->getMessage();
    exit;
}//fim conexao


$insert = $pdo->prepare("INSERT INTO pedido (id_empresa, data_pedido, data_entrega, estado, 
data_vencimento) VALUES (?, ?, ?, ?, ?)");
$insert->bindParam(1, $_SESSION['dados']['id_empresa']);
$insert->bindParam(2, $_SESSION['dados']['data_pedido']);
$insert->bindParam(3, $_SESSION['dados']['data_entrega']);
$insert->bindParam(4, $_SESSION['dados']['estado']);
$insert->bindParam(5, $_SESSION['dados']['data_vencimento']);
$insert->execute();
?>

That’s pretty much it, sorry about the big code. I thank you for your patience and I thank you so much who can help because I really need this to work.

  • 1

    It doesn’t make much sense... The cart items will be in a table, when clicking finish you recover these items without having to move from one page to another

  • 1

    I agree with @Papacharlie, keep a table with customers' orders(shopping cart), customers happen to initialize a purchase transaction on one device and end on another. If you use the client device to store or route this data it is restricted to finalize the purchase only in this device and browser and the data of this operation may be lost in case of customer’s equipment failure or browser memory cleaning.

1 answer

-1

So for what I know the easiest way to do this would be to store the data of the array in a COOKIE and then retrieve this information on the other page in the case "terminate.php", remembering that the COOKIES are stored in the client or in the browser of the user, but for this situation fits perfect because I believe you want to just pass this information to another page and then transfer it to the database. If you do not know how to use COOKIES and only search or go in the documentation is quite simple to use.

Browser other questions tagged

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