codeigniter undefined offset error - php

I'm currently learning cart system with CI and got some problems
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 2
Filename: models/main_model.php
Line Number: 241
here's the code:
Controller:
function update_cart(){
$this->main_model->validate_update_cart();
redirect('cart');
}
Model:
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], //this is line 241
'qty' => $qty[$i]
);
// Update the cart with the new information
$this->cart->update($data);
}
}
view:
<div id="main">
<?php if(!$this->cart->contents()):
echo 'You don\'t have any items yet.';
else:
?>
<?php echo form_open('cart/update_cart'); ?>
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<thead>
<tr>
<td style="background-color:yellow;">Qty</td>
<td style="background-color:yellow;">Item No/td>
<td style="background-color:yellow;">Description</td>
<td style="background-color:yellow;">Color</td>
<td style="background-color:yellow;">Price</td>
<td style="background-color:yellow;">Sub-Total</td>
<td style="background-color:yellow;">Delete</td>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
<?php foreach($this->cart->contents() as $items): ?>
<?php echo form_hidden('rowid[]', $items['rowid']); ?>
<tr <?php if($i&1){ echo 'class="alt"'; }?>>
<td>
<?php echo form_input(array('name' => 'qty[]', 'value' => $items['qty'], 'maxlength' => '3', 'size' => '5')); ?>
</td>
<td><a style="font-size:11px;"><?php echo $items['id']?></a></td>
<td><a style="font-size:11px;"><?php echo $items['name']; ?></a></td>
<td><a style="font-size:11px;"><?php echo $items['warna']?></a></td>
<td><a style="font-size:11px;">Rp. <?php echo number_format($items['price'],0,",",".");?></a></td>
<td><a style="font-size:11px;">Rp. <?php echo number_format($items['subtotal'],0,",",".");?></a></td>
<td><img src="<?= base_url();?>assets/image/hapus.png"></img></td>
</tr>
<?php $i++; ?>
<?php endforeach; ?>
<tr>
<td colspan="5"><strong>Total</strong></td>
<td colspan="2"><a align="right"><?php echo $this->cart->format_number($this->cart->total()); ?></a></td>
</tr>
</tbody>
</table>
<p><?php echo "<input type='submit' class='Button' value='Update'>";?></p>
<?php
echo form_close();
endif;
?>
edited the view, complete code.
when i click the update button it returned error live above.
thanks.

It seems that $this->cart->total_items() returns something different from the total items in the $item and $qty arrays. Later on, you are using this result to iterate these arrays, and the loop variable ($i) exceeds the arrays' boundaries.
Change your loop to:
for($i=0;$i < count($item);$i++)
You can choose count($qty) if you prefer, provided that the two arrays contain the same number of elements (which has to be true anyway, in order for the whole algorithm to work).

when you receive the post you should use
rowid[] instead of rowid

Related

Hide first <td> if second in <td> is not selected any value (empty)

I need hide first one < td > <?php echo $user_feature['tab_title_single']; ?> if second < td > are abolutely empty without any checked ('tab_title_labels') values.
<?php
if (!defined('ABSPATH')) {
exit; // Exit if accessed directly
}
if (!empty($id)) {
$post_id = $id;
}
$user_features = array(
array(
'tab_title_single' => 'Apsauga',
'tab_title_labels' => 'Imobilaizeris,Signalizacija,Palydovinė sekimo sistema,Šarvuotas (apsaugos)'
),
array(
'tab_title_single' => 'Audio/video įranga',
'tab_title_labels' => 'CD grotuvas,MP3 grotuvas,Papildoma audio įranga,CD keitiklis,AUX jungtis,Žemų dažnių garsiakalbis,DVD grotuvas,USB jungtis,Laisvų rankų įranga,Apple CarPlay / Android Auto'
),
array(
'tab_title_single' => 'Eksterjeras',
'tab_title_labels' => 'Lengvojo lydinio ratlankiai,LED dienos žibintai,LED žibintai,Žibintai „Xenon“,Rūko žibintai,Kablys,Priekinių žibintų plovimo įtaisas,Stogo bagažinės laikikliai,Automatiškai užsilenkiantys veidrodėliai,Žieminių padangų komplektas'
),
array(
'tab_title_single' => 'Elektronika',
'tab_title_labels' => 'El. valdomi veidrodėliai,El. valdomas bagažinės dangtis,Automatiškai įsijungiantys žibintai,Borto kompiuteris,El. reguliuojama vairo padėtis,Kritulių jutiklis,Šildomi veidrodėliai,Atstumo jutiklių sistema,Beraktė sistema,Autopilotas,El. šildomas priekinis stiklas,Start-Stop funkcija,Valdymas balsu,Pavarų perjungimas prie vairo,LCD ekranas,Navigacija/GPS'
)
);
?>
<?php if (!empty($user_features)) {
if (!empty($post_id)) {
$features_car = get_post_meta($post_id, 'additional_features', true);
$features_car = explode(',', $features_car);
} else {
$features_car = array();
}
foreach ($user_features as $user_feature) { ?>
<table style="width: 100%; margin-bottom: 0px">
<tr>
<td style="width: 16%; padding-left:5px;">
<div class="heading-font" style="color:#555555;font-size: 13px;font-weight: 500;"><?php echo $user_feature['tab_title_single']; ?></div>
</td>
<td style="width: 84%; padding-left:5px;">
<?php $features = explode(',', $user_feature['tab_title_labels']); ?>
<?php if (!empty($features)): ?>
<?php foreach ($features as $feature): ?>
<?php
$checked = '';
$hide = 'style="display:none;"';
if (in_array($feature, $features_car)) {
$checked = 'checked';
$hide = '';
};
?>
<label <?php echo $hide; ?>>
<span class="featuresspan"><?php echo esc_attr($feature); ?></span>
</label>
<?php endforeach; ?>
<?php endif; ?>
</td>
</tr>
</table>
<?php }
}
?>
To compare two arrays ($features and $features_car) in php, the most direct tool for that task is array_intersect(). Although I should tell you (and researchers) that it would be far, far better to Normalize your table data so that you are not storing comma-separated values. Having a normalized/granular table of labels and their individual features spread across multiple rows will allow your application to enjoy cleaner and more efficient queries and allow you to move the filtering processes from php to mysql where it belongs.
Code: (Demo)
$features_car = ['USB jungtis', 'Rūko žibintai'];
foreach ($user_features as $user_feature) {
$features = explode(',', $user_feature['tab_title_labels']);
$matched_features = array_intersect($features, $features_car);
if ($matched_features) {
echo "<table>";
echo "<tr>";
echo "<td>";
echo "<div class=\"heading-font\">{$user_feature['tab_title_single']}</div>";
echo "</td>";
echo "<td>";
foreach ($matched_features as $show_feature) {
echo "<label><span class=\"featuresspan\">{$show_feature}</span></label>";
}
echo "</td>";
echo "</tr>";
echo "</table>";
}
}
Output:
<table>
<tr>
<td>
<div class="heading-font">Audio/video įranga</div>
</td>
<td>
<label><span class="featuresspan">USB jungtis</span></label>
</td>
</tr>
</table>
<table>
<tr>
<td>
<div class="heading-font">Eksterjeras</div>
</td>
<td>
<label><span class="featuresspan">Rūko žibintai</span></label>
</td>
</tr>
</table>
p.s. I don't know if I support the stacking of <table> elements like this, but it is up to you how you wish to style your markup. You should move ALL of your inline styles to an external stylesheet so that your markup is easier to read and manage. I removed the esc_attr() only so that my demo would work without errors -- you can safely apply it to all variables that you are concerned about.

How to delete specific session record by clicking on href?

I unable to delete specific record from session array. I want to delete specific row in table when I click on delete link.
<?php
session_start();
if(isset($_GET["product"]) && isset($_GET["category"])){
$nomProduct = trim($_GET["product"]);
$category = trim($_GET["category"]);
$_SESSION['product'][] = array(
"nomProduct" => $nomProduct ,
"category" => $category
);
//session_destroy();
}
?>
html table
<table class="table">
<?php foreach($_SESSION["product"] as $items) { ?>
<tr>
<th width="250px"><?php echo $items['nomProduct']; ?></th>
<td><?php echo $items['category']; ?></td>
<td style="text-align: right">Delete<td>
</tr>
<?php }?>
</table>
`
$key=array_search($_GET['product'],$_SESSION['product']);
if($key!==false)
unset($_SESSION['product'][$key]);
$_SESSION["product"] = array_values($_SESSION["product"]);
`
Maybe this might help!
You need to find the key as this is an array.
EDIT:
Made an example for you, here when you click the link, it deletes the first name from the session array.
<?php
session_start();
$_SESSION["user"] = ["fname"=>"William","lname"=>"Henry" ];
if(isset($_GET["delete"]))
{
if($_GET["key"])
{
$key=$_GET["key"];
unset($_SESSION['user'][$key]);
}
}
?>
HTML on the same page
<h1>
<?php
if(isset($_SESSION["user"]["fname"]))echo $_SESSION["user"]["fname"]." ";
if(isset($_SESSION["user"]["lname"]))echo $_SESSION["user"]["lname"];
?>
</h1>
Delete First Name
If you want to delete the lastname (lname), change the key=lname in the href of the link, hope this example helps in your case
Modify your HTML
<table class="table">
<?php foreach($_SESSION["product"] as $key => $items) { ?>
<tr>
<th width="250px"><?php echo $items['nomProduct']; ?></th>
<td><?php echo $items['category']; ?></td>
<td style="text-align: right">Delete<td>
</tr>
<?php }?>
</table>
Catch the array key and remove it from session array.
$key = filter_input(INPUT_GET, 'key');
unset($_SESSION['product'][$key]);

Can't get the value of a data PHP

im having trouble getting a result value of a query and the error says.
Notice: Undefined index: prelim in C:\xampp\htdocs\gradingxworking\teacher\student.php on line 85 can someone help me to fix this or some clue to fix this? im just starting to learn php.
<tbody>
<?php $c=1; ?>
<?php foreach($mystudent as $row): ?>
<tr>
<td><?php echo $c; ?></td>
<td class="text-center"><?php echo $row['studid']; ?></td>
<td class="text-center"><?php echo $row['lname'].', '.$row['fname']; ?></td>
<?php $grade = $student->getstudentgrade($row['studid']);?>
//code that cause error line 85--> <td class="text-center"><?php echo $grade['prelim']; ?></td>
</tr>
<?php $c++; ?>
<?php endforeach; ?>
<?php if(!$mystudent): ?>
<tr><td colspan="8" class="text-center text-danger"><strong>*** No Result ***</strong></td></tr>
<?php endif; ?>
</tbody>
the function:
function getstudentgrade($studid){
$q = "select * from studentsubject where studid=$studid";
$r = mysql_query($q);
$data = array();
while($row = mysql_fetch_array($r)){
$data[] = array(
'prelim' => $row['prelim']
);
}
return $data;
}
As #Bara suggested, you need to check the array first before accessing it.
if(isset($grade['prelim']))
I suspect, there is no data for specific studid. Lets see you function.
$data = array();
while($row = mysql_fetch_array($r)){
$data[] = array(
'prelim' => $row['prelim']
);
}
Now, you have created new array $data. But, if there is no record ? your while loop won't be executed and your $data array won't have anything. right ? So, to handle that, you need to check whether there is any data in your array.
Now, second point, which #Mossavari made is also correct. You need to use
$grade[0]['prelim'];
instead of
$grade['prelim'];
after doing
<?php $grade = $student->getstudentgrade($row['studid']);?>
you need to check what $grade holdes. and its better before trying to fetch data from array to make a check like this :
if(isset($grade['prelim']))
Based on your getstudentgrade function you'll have multidimensional array result, you may need to change $grade['prelim'] to $grade[0]['prelim']
Since, every student will have only 1 grade. So, why to use array.
<?php
function getstudentgrade($studid){
$q = "select * from studentsubject where studid=$studid LIMIT 0,1";
$data = "";
$r = mysql_query($q);
while($row = mysql_fetch_array($r)){
$data = $row['prelim'];
}
return $data;
}?>
PHP
<tbody>
<?php $c=1; ?>
<?php foreach($mystudent as $row): ?>
<tr>
<td><?php echo $c; ?></td>
<td class="text-center"><?php echo $row['studid']; ?></td>
<td class="text-center"><?php echo $row['lname'].', '.$row['fname']; ?></td>
<td class="text-center"><?php echo $grade = $student->getstudentgrade($row['studid']);?></td>
</tr>
<?php $c++; ?>
<?php endforeach; ?>
<?php if(!$mystudent): ?>
<tr>
<td colspan="8" class="text-center text-danger">
<strong>*** No Result ***</strong>
</td>
</tr>
<?php endif; ?>
</tbody>

Why in my post is only one item? CakePHP 2.x

I have table in my view. This table is in form. I need send all items from table to my controller. I create form but he is sending only one item, last item...
Here is my table in View:
<?php echo $this->Form->create('Goodsandoffer');?>
<table id="GoodSandOffersTable" class="display" cellspacing="0" width="100%">
<thead><tr>
<th><?php echo $this->Paginator->sort('id','ID'); ?></th>
<th><?php echo $this->Paginator->sort('nazwa','Nazwa'); ?></th>
<th><?php echo $this->Paginator->sort('kodKreskowy','Kod EAN'); ?></th>
<th><?php echo $this->Paginator->sort('cenaSprzedazyBrutto','Cena sprzedaży brutto'); ?></th>
<th>Cena Promocyjna</th>
<th>Akcja</th>
</tr>
</thead>
<tbody>
<?php $x =0;?>
<?php foreach ($goods as $good): ?>
<tr>
<td><?php echo h($goodID= $good['Good']['id']);?></td>
<td><?php echo h($good['Good']['nazwa']);?></td>
<td><?php echo h($good['Good']['kodKreskowy']);?></td>
<td><?php echo h($good['Good']['cenaSprzedazyBrutto']);?></td>
<?php echo $this->Form->input('promotionaloffer_id',array("default"=>$prom['Promotionaloffer']['id'],'type'=>'hidden'));?>
<?php echo $this->Form->input('good_id',array("default"=>$good['Good']['id'],'type'=>'hidden'));?>
<td><?php echo $this->Form->input('cenaPromocyjna', array('id' => 'cenaPromocyjna'.$x));?></td>
</tr>
<?php $x = $x + 1 ;?>
<?php endforeach; ?>
</tbody>
</table>
<?php echo $this->Form->end(__('Dodaj')); ?>
Here is controller:
if ($this->request->is('post')) {
debug($this->request->data);
}
And when Im debug I got this:
\app\Controller\GoodsandoffersController.php (line 110)
array(
'Goodsandoffer' => array(
'promotionaloffer_id' => '3',
'good_id' => '20',
'cenaPromocyjna' => '3'
)
)
In array I have only last item from table. I need all. What Im doing wrong?
I'm not familiar with CakePHP myself but it looks like all your fields in your table rows have the same name (promotionaloffer_id, good_id, cenaPromocyjna):
<?php echo $this->Form->input('promotionaloffer_id',array("default"=>$prom['Promotionaloffer']['id'],'type'=>'hidden'));?>
<?php echo $this->Form->input('good_id',array("default"=>$good['Good']['id'],'type'=>'hidden'));?>
<td><?php echo $this->Form->input('cenaPromocyjna', array('id' => 'cenaPromocyjna'.$x));?></td>
In order to receive all values, you need to indicate them with array keys like so:
<?php echo $this->Form->input('promotionaloffer_id['.$good['Good']['id'].']',array("default"=>$prom['Promotionaloffer']['id'],'type'=>'hidden'));?>
<?php echo $this->Form->input('good_id['.$good['Good']['id'].']',array("default"=>$good['Good']['id'],'type'=>'hidden'));?>
<td><?php echo $this->Form->input('cenaPromocyjna['.$good['Good']['id'].']', array('id' => 'cenaPromocyjna'.$x));?></td>
This would result in input names like
promotionaloffer_id[0], good_id[0], cenaPromocyjna[0]
promotionaloffer_id[1], good_id[1], cenaPromocyjna[1]
...
promotionaloffer_id[x], good_id[x], cenaPromocyjna[x]
Where x is the good-id.

Call function throught another file

View/Invoice/View.ctp
<?php
if ( $payments == NULL ) {
echo '<tr><td> -- No Payments Are Associated With This Invoice -- </td>
<td></td>
<td></td></tr>';
}
?>
<? foreach ($payments as $payment): ?>
<tr id="payment_row_<?= $payment['id'] ?>">
<td class="responsive_cell"><?php echo $payment['method']?></td>
<td class="date_cell responsive_cell"><?php echo $payment['date']?></td>
<td class="right responsive_cell"><?php echo number_format($payment['amount'], 2, '.', ',')?></td>
</tr>
<?php $paymentsTotal += $payment['amount'] ?>
<? endforeach; ?>
View/Invoice/email.ctp
$bedrag = $settings['Setting']['currency'].$thisInvoice['Payment'];
This echo's €Array in EMail.ctp and in View.ctp show the right amount.
How do i get the right amount in Email.ctp ?

Categories