PHP 中的用户定义按钮

User defined button in PHP

所以我想做一个购物车。我需要做的是将用户想要购买的产品 ID 和数量发送到另一个文件 cart.php.

这是我的代码的一部分:

for($i=0;$i<$numOfRows;$i++){
  $prodID=mysql_result($result, $i, "ProductID");
  $prodTitle=mysql_result($result, $i, "Title");
  $prodAuthor=mysql_result($result, $i, "Author1");
  $prodPrice=mysql_result($result, $i, "Price");

  Print"<h4>ID: $prodID \n     </h4>";
  Print"<h4>Title: $prodTitle \n       </h4>";
  Print"<h4>Author: $prodAuthor \n     </h4>";
  Print"<h4>Price: $ $prodPrice \n     </h4>";

  Print" <form method ='POST'>";
  Print"<p><label> Quantity";
  Print"<input name='quantity' type='text' pattern='[1-9]{1,50}'/>";
  Print"</label>";
  Print"<input type='button' value='Add To Cart' onClick='cart.php?pid=$prodID'/>";
  Print"</p></form>";
}

如果我摆脱表格而只使用 <a href='cart.php?pid=$prodID'>Add To Cart</a> 它会发送 ID,但我还需要数量来配合它。 每当我单击 添加到购物车 时,它不会将我发送到我的 cart.php.

您的 onlick 正在执行 GET 方法,而您的表单指示方法 POST 而您没有在表单标记中指定 "action='cart.php'"...可能还有其他问题,但是...

试试这个

for($i=0;$i<$numOfRows;$i++)
{
   $prodID=mysql_result($result, $i, "ProductID");
   $prodTitle=mysql_result($result, $i, "Title");
   $prodAuthor=mysql_result($result, $i, "Author1");
   $prodPrice=mysql_result($result, $i, "Price");

   Print"<h4>ID: $prodID \n    </h4>";
   Print"<h4>Title: $prodTitle \n      </h4>";
   Print"<h4>Author: $prodAuthor \n    </h4>";
   Print"<h4>Price: $ $prodPrice \n    </h4>";

   Print"<form action='cart.php' method ='POST'>";
   Print"<p><label> Quantity";
   Print"<input name='pid' type = 'hidden' value='$prodID'>";
   Print"<input name='quantity' type='text' pattern='[1-9]{1,50}'/>";
   Print"</label>";
   Print"<input type='submit' value='Add To Cart'>";
   Print"</p></form>";
}

为什么不让它正常提交表单呢。并使用 type="submit"method="GET":

echo "<form method ='GET' action='cart.php'>";
    echo "<p><label> Quantity: ";
        echo "<input name='quantity' type='text' pattern='[1-9]{1,50}'/>";
    echo "</label>";
    echo "
        <input type='hidden' name='pid' value='$prodID' />
        <input type='submit' value='Add To Cart' />
    ";
echo "</p></form>";

当然在 cart.php 中,只需使用 $_GET 即可:

<?php

if(!empty($_GET['quantity']) && !empty($_GET['pid'])) {
    $quantity = $_GET['quantity'];
    $pid = $_GET['pid'];
    // do the rest of codes below
}

必填项:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

如果您想使用 POST 方法,请添加带有 pid 信息的隐藏输入。看例子:

print" <form method ='POST' action ='cart.php'>";
print"<p><label> Quantity";
print"<input name='quantity' type='text' pattern='[1-9]{1,50}'/>";
print"</label>";
print"<input type='hidden' name = 'pid' value='$prodID'>";
print"<input type='button' value='Add To Cart'/>";
print"</p></form>"; 

如果您想使用 GET 方法,请参阅 答案