The isset function only works on the first checkbox in the database
P粉787820396
2023-09-05 22:42:25
<p>我有一个组件,它从MySQL数据库中获取所有数据。</p>
<pre class="brush:php;toolbar:false;"><?php
function component($productName, $productPrice, $productImg, $productID)
{
$element = "
<div class='col-md-3 col-sm-6 my-3 my-md-0'>
<form action='index.php' method='post' id='myform'>
<div class='card shadow'>
<img src='{$productImg}' alt='image1' class='img-fluid card-img-top'>
<div class=\"card-body\">
<h5 class='card-title'>{$productName}</h5>
</div>
<p class='card-text'>info goes here lorem ipsum</p>
<span class='price'>{$productPrice}</span>
<span class='price'>{$productID}</span>
<div class='form-check form-switch'>
<input class='form-check-input' type='checkbox' name='checkid[]' value='{$productID}'>
</div>
<input type='hidden' name='product_id' value='{$productID}'>
</div>
</form>
</div>
";
echo $element;
}</pre>
<p>我还有一个用于表单的提交按钮。
<code><button type="submit" name="submit" form="myform">显示所选内容</button></code></p>
<p>获取容器的代码:</p>
<pre class="brush:php;toolbar:false;"><div class="container">
<div class="row text-center py-5">
<?php
$result = $database->getData();
while ($row = mysqli_fetch_assoc($result)) {
component($row['product_name'], $row['product_price'], $row['product_image'], $row['id']);
}
?>
</div></pre>
<p>当点击提交按钮时,用于检查容器是否被选中并返回其值(productID)的PHP代码。</p>
<pre class="brush:php;toolbar:false;">if (isset($_POST['submit'])) {
if (!empty($_POST['checkid'])) {
foreach ($_POST['checkid'] as $value) {
echo "value : " . $value . '<br/>';
}
}
}</pre>
<p>我在数据库中有几个产品,但它只适用于第一个复选框。其他的不起作用。</p>
You create a new form element each time you loop through it. You can change your function to
And the code to get your component (function above) and submit button in a separate form, as follows: