通过PDO连接添加到新表时出现问题

时间:2018-10-28 08:33:49

标签: php mysql

我是PHP的新手,我正在尝试使用PDO连接将表中的元素插入到另一个表中。我有一个产品表,该产品表显示在我的产品页面上,当我选择其中一个产品时,我希望将产品ID和数量添加到具有自己的表的购物车中。我现在遇到的问题是我无法在购物车表中添加任何内容。有人对如何解决这个问题有任何想法吗?谢谢。

products.php

<?php 
$pdo = new PDO(
  "mysql:host=localhost;dbname=Shopping_cart;charset=utf8",
  "root",
  "root"
  );


    $statement = $pdo->prepare("SELECT * FROM products");
    $statement->execute();

    $products = $statement->fetchAll(PDO::FETCH_ASSOC);

    ?>

    <?php foreach ($products as $single_product) : ?>

    <div class="col-sm-12 col-md-4 mb-4">
          <div class="card h-100">
          <form action="index.php" method="POST">
              <img class="card-img-top" src="<?= $single_product['img']; ?>">
              <div class="card-body">
                <h4 class="card-title" id="title_name"><?= $single_product['name']; ?></h4>
                <h5 name="price"><?= $single_product['price'] . ' kr'; ?></h5>
                <p class="card-text"><?= $single_product['descr']; ?></p>
              </div> 
              <div class="card-footer">
              <label for="amount">Choose Amount</label>
              <input type="text" name="quantity" id="amount">
              <input type="hidden" name="prod_id" value="<?= $single_product['product_id']; ?>">
              <input type="submit" name="add_to_cart" class="removeOrBuy" value="Add To Cart">

              </div> 
              </form>
          </div><!--h-100-->
        </div><!--col-sm-12-->

addtocart.php

  <?php

  $pdo = new PDO(
  "mysql:host=localhost;dbname=Shopping_cart;charset=utf8",
  "root",
  "root"
  );

       if(isset($_POST['add_to_cart'])) {
          $prod_id = $_POST['prod_id'];
          $quantity = $_POST['quantity'];

           $statement = $pdo->prepare(
            "INSERT INTO cart (product_id, quantity)
            SELECT (product_id, quantity) FROM products"
            );
            $statement->execute(
             [
               ":quantity" => $quantity,
               "product_id" => $prod_id
             ]
            );
          }

         header('Location: index.php');   


        ?>

1 个答案:

答案 0 :(得分:0)

您的INSERT语句语法不正确,请使用...

   $statement = $pdo->prepare(
        "INSERT INTO cart (product_id, quantity)
                   VALUES (:product_id, :quantity)"
        );

您的form也有...

<form action="index.php" method="POST">

不会调用其他脚本...

<form action="addtocart.php" method="POST">