我有一个产品库,其中显示了数据库中的产品。它们有productID product_name product_price etc和每个产品上的产品详细信息下的复选框。我想要的功能是,当我选中多个产品时,它们应该使用唯一的用户ID添加到选择表中。
<form action="add_selection_script.php" method="POST" enctype="multipart/form-data">
<select class="form-select tw-capitalize" name="u_id">
<option value="">Select a Customer</option>
<?php
$get_users = "SELECT * FROM users";
$run_users = mysqli_query($con, $get_users);
while ($row_users = mysqli_fetch_array($run_users)) {
$u_id = $row_users['u_id'];
$username = $row_users['user_username'];
echo "<option value='$u_id'>$username</option>";
}
?>
</select>
<?php
$get_products = "SELECT * FROM products";
$run_products = mysqli_query($con, $get_products);
while ($row_products = mysqli_fetch_array($run_products)) {
$id = $row_products['id'];
$pro_id = $row_products['product_id'];
$pro_cat = $row_products['product_cat'];
$pro_title = $row_products['product_title'];
$pro_size = $row_products['product_size'];
$pro_price = $row_products['product_price'];
$pro_image = $row_products['product_image'];
?>
<div class="col-lg-2 col-12">
<input type="hidden" name="price" value="">
<input type="hidden" name="product_title" value="<? echo $pro_title; ?>">
<input type="hidden" name="product_image" value="<? echo $pro_image; ?>">
<div class="card mb-3">
<div class="tw-aspect-w-4 tw-aspect-h-4">
<img src="../includes/product_images/<? echo $pro_image ?>" class="card-img-top" alt="...">
</div>
<div class="card-body">
<h5 class="card-title"><? echo $pro_title ?></h5>
<p class="card-text mb-3">Price <? echo $pro_price ?> EUR</p>
<a href="#" class="btn btn-primary">Go somewhere</a>
</div>
<div class="card-footer">
<div class="form-check mb-2">
<input type="checkbox" class="form-check-input" name="pid[]" id="<?echo $pro_id?>" value="<?echo $pro_id?>">
<label class="form-check-label" for="<?echo $pro_id?>">
Select
</label>
</div>
</div>
</div>
</div>
<? } ?>
</form>
在我的add_selection_script.php
里
<?php
include '../includes/conn.php';
if (isset($_POST['insert_selection'])) {
$u_id = $_POST['u_id'];
$tradexx_price = $_POST['tradexx_price'];
$product_title = $_POST['product_title'];
$product_image = $_POST['product_image'];
$pid = implode(',', $_POST['pid']);
$insert_selection = "INSERT INTO selection (c_id,p_id,tradexx_price,pvp,product_name,img) VALUES ('$u_id','$checkBox','$tradexx_price','$pvp','$product_title','$product_image')";
echo $insert_selection;
die();
$insert_sel = mysqli_query($con, $insert_selection);
if ($insert_sel) {
echo "<script>alert('Selection has been added!')</script>";
echo "<script>window.open('add_selection.php', '_self')</script>";
}
}
?>
我可以得到pid
逗号分隔的形式,但我怎么能得到其他人?我不擅长PHP,并试图弄清楚它。我的目标是插入所有选中的产品作为数据库中的单独条目。谢谢
1条答案
按热度按时间ruarlubt1#
现在你有一个循环:
这会让您多次使用相同的名称
price
,这是行不通的。我认为处理这一问题的最佳方法是使用产品ID作为复选框的值:然后,在处理表单的页面中,只需循环数组即可:
我还注意到,您插入的所有值都来自
hidden
表单元素。不要这样做。即使这些值是隐藏的,也不会阻止用户提供新值。相反,只需获取产品ID,然后在插入时查找关联的值。如下所示: