使用Codeigniter 3和本机购物车库。当我更改数量并更新购物车时,如果我从1更改为2,它可以正常工作。如果我改为3或更高,我会得到错误,虽然它仍然将数量更新为3.如果我然后改回1我得到错误,一旦回到1我再次改为2确定。
错误:
Severity: Notice
Message: Undefined offset: 1
Filename: models/Cart_model.php
Line Number: 60
第60行是
'rowid' => $item[$i]
购物车:
<?php echo form_open('cart/update'); ?>
<table class="table">
<thead>
<tr>
<th class="text-center"><i class="fa fa-shopping-cart"></i>
</th>
<th>Product Name</th>
<th>Quantity</th>
<th>Total</th>
<th></th>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
<?php foreach ($this->cart->contents() as $items): ?>
<?php echo form_hidden('rowid[]', $items['rowid']); // We added an hidden field which contains a unique id in array format, this is needed in order to update ?>
<tr>
<td class="table-first">
<img class="img-responsive" src="<?= site_url('assets/images/shop/CreamseedBoilies.jpg') ?>" alt=""/>
</td>
<td>
<span class="title"><?php echo $items['name']; ?></span>
</td>
<td>
<?php echo form_input(array('name' => 'qty[]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?>
</td>
<td>
<span><?php echo $this->cart->format_number($items['price']); ?></span>
</td>
<td class="close-cart">
<a href="<?= site_url('cart/remove/'.$items['rowid']) ?>" class="btn btn-primary btn-sm"><i class="fa fa-times"></i>
</a>
</td>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
</tbody>
</table>
<div class="panel-footer">
<div class="row">
<div class="col-sm-3">
<a href="<?= site_url('cart/empty') ?>" class="btn btn-default btn-sm">Empty Cart</a>
</div>
<div class="col-sm-9 text-right">
<button type="submit" class="btn btn-default btn-sm">Update Cart</button>
<a href="#" class="btn btn-primary btn-sm">Proceed to checkout</a>
</div>
</div>
</div>
<?php echo form_close() ?>
购物车更新方法:
public function update()
{
$this->cart_model->validate_update_cart();
redirect('cart');
}
购物车型号:
function validate_update_cart(){
// Get the total number of items in cart
$total = $this->cart->total_items();
// Retrieve the posted information
$item = $this->input->post('rowid');
$qty = $this->input->post('qty');
// Cycle true all items and update them
for($i=0;$i < $total;$i++)
{
// Create an array with the products rowid's and quantities.
$data = array(
'rowid' => $item[$i],
'qty' => $qty[$i]
);
// Update the cart with the new information
$this->cart->update($data);
}
}
答案 0 :(得分:0)
原来:
$total = $this->cart->total_items();
不提供总计独特的产品(rowid),而是提供包含一种产品的倍数的项目。因此,$ total和total items的大小并不匹配。
正确的方式:
function validate_update_cart(){
// Get the total number of items in cart
// Retrieve the posted information
$item = $this->input->post('rowid');
$qty = $this->input->post('qty');
$total = count($item);
// Cycle true all items and update them
for($i=0;$i < $total;$i++)
{
// Create an array with the products rowid's and quantities.
$data = array(
'rowid' => $item[$i],
'qty' => $qty[$i]
);
// Update the cart with the new information
$this->cart->update($data);
}
}