我在 View 中有这个表单:
Your Name: <input type="name" name="name" id="name" ><br><br>
Your Contact No. <input type="contact" name="contact" id="contact" ><br><br>
Todays date:<mark>{{$mytime->format('Y-m-d, l')}}</mark><br><br>
<br><br>BOOK SEATS:<br>
@foreach($seats as $seat)
@if($seat->available=='1')
<input type="checkbox" name="check[]" value="{{$seat->book}}" >{{$seat->book}}<br><br>
@else
<input type="checkbox" name="check[]" value="{{$seat->book}}" disabled>{{$seat->book}}<br><BR>
@endif
@endforeach
<button type="submit" class="btn btn-default">Book</button>
</form>
此表单重定向到此 Controller ,该 Controller 插入名称联系人和使用循环检查的复选框的值。这样,如果我检查两个值并提交表单,由于 for 循环,将插入具有相同 name
contact
但具有不同 booked_seats
的两行> 和 id
(我使用 id 作为自动递增)。有什么方法可以将选中的值插入到只有一行的 booked_seats 中。或者使 id
与当时插入的任何行(检查值)相同。
public function book(Request $request)
{
$name=$request->get('name');
$contact=$request->get('contact');
$check=$request->get('check');
$totalcheckboxchecked=sizeof('$check');
for($i=0;$i<=$totalcheckboxchecked;$i++)
{
if (array_key_exists($i,$check) )
{
$booked=$check[$i];
$book=bus::insert(['name'=>$name,'contact'=>$contact, 'booked_seats'=>$booked, 'active'=>'1']);
seats::where('book',$booked)->update(['available'=>'0']);
}
}
return redirect('/bus')
->with('message','booked successfully!!!');
}
最佳答案
您可以使用序列化将选中的值存储在数据库中
$booked = serialize ($check);
然后你可以像这样保存在数据库中而不使用for循环
$book=bus::insert(['name'=>$name,'contact'=>$contact, 'booked_seats'=>$booked, 'active'=>'1']);
seats::where('book',$booked)->update(['available'=>'0']);
要重新检索值,请使用反序列化
unserialize($booked);
这是完整的代码。
public function book(Request $request)
{
$name=$request->get('name');
$contact=$request->get('contact');
$check=$request->get('check');
$checkarray = serialize($check);
$totalcheckboxchecked=sizeof('$check');
for($i=0;$i<=$totalcheckboxchecked;$i++)
{
if (array_key_exists($i,$check) )
{
$booked=$check[$i];
seats::where('book',$booked)->update(['available'=>'0']);
}
$book=bus::insert(['name'=>$name,'contact'=>$contact, 'booked_seats'=>$checkarray, 'active'=>'1']);
}
return redirect('/bus')
->with('message','booked successfully!!!');
}
关于php - 在数据库列中存储数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37370327/