我有一个名为qty
的输入字段,该值必须传递给名为update_cart的下一页进行处理。我尝试使用会话变量。但是,当我尝试通过$_Post
或$_Get
发送时,它无法正常工作。请给我任何建议。我试过的代码如下:
cart.php
echo "<table class='table table-hover table-responsive table-bordered'>";
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price (USD)</th>";
echo "<th>Quantity</th>";
echo "<th>Action</th>";
echo "<th>Updated price</th>";
echo "</tr>";
$query = "SELECT * FROM sub_products WHERE sub_p_id IN ({$ids}) ORDER BY name";
$stmt = $con->prepare( $query );
$stmt->execute();
$total_price=0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
echo "<tr>";
echo "<td>".$row['name']."</td>";
echo "<td>$".$row['price']."</td>";
echo "<td>";
echo "<input type='number' name='qty' value='' max='10'>";
$_SESSION['qty']=2 ; //here i want to pass value of "qty"
echo "<a href='update_cart.php?id={$id}&name=".$row['name']."&price=".$row['price']."&qty=".$_SESSION['qty']."' class='btn btn-danger'>";
echo "<span </span> Update Price </a>";
$total_price+=$price;
}
echo "<tr>";
echo "<td><b>Total</b></td>";
echo "<td>${$total_price}</td>";
update_cart.php
session_start();
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$qty=$_SESSION['qty'];
$price=isset($_GET['price'])? $_GET['price']: "";
$price=$price*$qty;
echo $qty;
header('Location: cart.php?action=quantity_updated&id=' . $id . '&name=' . $name . '&price='.$price . '&qty='.$qty);
答案 0 :(得分:1)
您首先要从GET
变量中获取数量。
$qty = isset($_GET['qty']) ? $_GET['qty'] : 1;
$_SESSION['qty'] = $qty;
或简化:
$_SESSION['qty'] = isset($_GET['qty']) ? $_GET['qty'] : 1;
如果不提交表单,则无法向变量添加值,因为PHP是服务器端语言。只要显示页面,PHP就会完成它并且无法更改。
为了让您更轻松,我将向您展示如何使用表单。
echo "<table class='table table-hover table-responsive table-bordered'>";
echo "<tr>";
echo "<th class='textAlignLeft'>Product Name</th>";
echo "<th>Price (USD)</th>";
echo "<th>Quantity</th>";
echo "<th>Action</th>";
echo "<th>Updated price</th>";
echo "</tr>";
$query = "SELECT * FROM sub_products WHERE sub_p_id IN ({$ids}) ORDER BY name";
$stmt = $con->prepare( $query );
$stmt->execute();
$total_price=0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
?>
<tr>
<form method="POST" action="update_cart.php">
<td><?= $row['name']; ?></td>
<td>$ <?= $row['price']; ?></td>
<td>
<input type='number' name='qty' value='' max='10'>
</td>
<td>
<input type="submit" name="submit" value="Submit">
</td>
<input type="hidden" name="id" value="<?= $row['id']; ?>" />
<input type="hidden" name="name" value="<?= $row['name']; ?>" />
<input type="hidden" name="price" value="<?= $row['price']; ?>" />
</form>
</tr>
变化:
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
$qty=$_SESSION['qty'];
$price=isset($_GET['price'])? $_GET['price']: "";
$price=$price*$qty;
为:
$id = isset($_POST['id']) ? $_POST['id'] : "";
$name = isset($_POST['name']) ? $_POST['name'] : "";
$qty=$_SESSION['qty'];
$price=isset($_POST['price'])? $_POST['price']: "";
$price=$price*$qty;