我正在尝试将数据/值插入到我的数据库中。
它可以工作,但问题是每次我只选择第二个值/复选框时,它的其他输入值会得到第一个输入的值。
<form action="{{url('/reservation')}}" method="post">
@csrf
<div class="row col-12">
<div>
<p class='mybox text-dark'><input type="checkbox" name="prod_name[]" value="JasminBooks"/>JasminBooks</p>
</div>
<div>
<input type="number" name="prod_qty[]" min="1" value="1"class="form-control ml-2">
</div>
<div class="row col-12">
<div>
<p class='mybox text-dark'><input type="checkbox" name="prod_name[]" value="KnowHowBooks"/>KnowHowBooks</p>
</div>
<div>
<input type="number" name="prod_qty[]" min="1" value="1"class="form-control ml-2">
</div>
</div>
</form>
这是我的控制器函数的代码
public function reservation(Request $request)
{
$data = new reservation;
$data->name = $request->name;
$data->email = $request->email;
$data->phone = $request->phone;
$data->address = $request->address;
$data->date = $request->date;
$data->time = $request->time;
$products = null;
$checked_array = $_POST['prod_name'];
foreach($_POST['prod_name'] as $key => $value) {
if (in_array($_POST['prod_name'][$key], $checked_array)) {
$products .= $_POST['prod_qty'][$key]." ".$_POST['prod_name'][$key].", ";
}
}
$data->products = $products;
$data->save();
return redirect()->back();
}
当
我应该在我的代码中添加/更改什么?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
这是因为你是根据索引来定义你的数量字段的。如果一个输入缺失,可能会影响你的整个结果。使用值作为键:
HTML:
<div> <p class='mybox text-dark'><input type="checkbox" name="prod_name[]" value="JasminBooks"/>JasminBooks </p></div><div> <input type="number" name="prod_qty[JasminBooks]" min="1" value="1"class="form-control ml-2"> </div>PHP:
$products = ''; $checked_array = $request->input('prod_name', []); $quantities = $request->input('prod_qty', []); foreach ($checked_array as $value) { if (array_key_exists($value, $quantities)) { $products .= "{$quantities[$value]} {$value}, "; } } // 移除末尾的 ', ' if (! empty($products)) { $products = substr($products, 0, -2); } $data->products = $products;P.S. 像 Bhaumik 说的那样,在 Laravel 中不要使用
$_POST。