Remove array from multidimensional array yii ajaxlink - ajax

I have a page to add items to a table that is rendered with renderpartial via ajax. Every time the user adds an item, I render the table with all the items. I also have an ajaxlink to delete the item the user chooses. The problem is that I can only delete the last record of the table, if I click on other ajaxlink, nothing happens.
here is the view file to search and add items
<div class="row">
<?php $this->widget('zii.widgets.jui.CJuiAutoComplete', array(
'name' => 'test_autocomplete',
'source'=>$this->createUrl('insumos/ver'),
'value' => "",
'options' => array(
'minChars'=>1,
'autoFill'=>false,
'focus'=> 'js:function( event, ui ) {
$( "#test_autocomplete" ).val( ui.item.label );
return false;
}',
'select'=>'js:function( event, ui ) {
$( "#Pedidos_codigoinsumo").val(ui.item.id);
$( "#Pedidos_codigo").val(ui.item.codigo);
$( "#Pedidos_nombre").val(ui.item.label);
$( "#Pedidos_cantidad").focus();
$( "#cantidades").show();
return false;
}',
),
'htmlOptions'=>array( 'autocomplete'=>'off'),
)); ?>
</div>
<div id="cantidades">
<div class="row">
<?php echo $form->labelEx($model,'codigo'); ?>
<?php echo $form->textField($model,'codigo',array('size'=>60,'maxlength'=>300)); ?>
<?php echo $form->hiddenField($model,'codigoinsumo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'nombre'); ?>
<?php echo $form->textField($model,'nombre',array('size'=>60,'maxlength'=>300)); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'cantidad'); ?>
<?php echo $form->textField($model,'cantidad',array('size'=>60,'maxlength'=>300)); ?>
<?php echo $form->error($model,'codigoinsumo'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'observaciones'); ?>
<?php echo $form->textArea($model,'observaciones',array('rows'=>6, 'cols'=>50)); ?>
</div>
<?php echo CHtml::ajaxButton('Agregar', array('pedidos/adicion'), array('type'=>'POST','data'=>'js:$("#pedidoalmacen-form").serialize()','update'=>'#req_res02'));
echo CHtml::ajaxButton('Cancelar Pedido', array('pedidos/cancelar'), array('update'=>'#req_res02'));
?>
<?php $this->endWidget(); ?>
<div id="req_res02"></div>
the view that has the table is:
if($ver==1)
{
?>
<table>
<tr>
<td align="center">Borrar</td>
<td align="center">Código</td>
<td align="center">Insumo</td>
<td align="center">Cantidad</td>
<td align="center">Observaciones</td>
</tr>
<?php
$codigo= Yii::app()->session['pedido-codigo'];
$contado=count($codigo);
$i=0;
while($i<$contado)
{
?>
<tr>
<td align="left"><?php echo CHtml::ajaxLink('Quitar', Yii::app()->createUrl('pedidos/quitar'),array('update'=>'#req_res02','type'=>'POST','data'=>array('dato'=>$codigo[$i]['contador'])),array('id'=>'quitar-'. uniqid())); ?></td>
<td align="left"><?php echo $codigo[$i]['contador']; ?></td>
<td align="left"><?php echo $codigo[$i]['insumo']; ?></td>
<td align="left"><?php echo $codigo[$i]['cantidad']; ?></td>
<td align="left"><?php echo $codigo[$i]['observaciones']; ?></td>
</tr>
<?php
$i++;
}
?>
</table>
<div class="row buttons">
<?php echo CHtml::submitButton('Agregar'); ?>
</div>
<?php
}
?>
and the controller is
public function actionAdicion()
{
$model=new Pedidos;
if(isset($_POST['Pedidos']))
{
$model->attributes=$_POST['Pedidos'];
if(isset(Yii::app()->session['pedido-codigo']))
{
$codigo= Yii::app()->session['pedido-codigo'];
$contador=count($codigo)+1;
$auxiliar=array('contador'=>$contador,'id'=>$model->codigoinsumo,'codigo'=>$model->codigo,'insumo'=>$model->nombre,'cantidad'=>$model->cantidad,'observaciones'=>$model->observaciones);
}
else
{
$auxiliar=array('contador'=>1,'id'=>$model->codigoinsumo,'codigo'=>$model->codigo,'insumo'=>$model->nombre,'cantidad'=>$model->cantidad,'observaciones'=>$model->observaciones);
}
$codigo[]=$auxiliar;
Yii::app()->session['pedido-codigo']=$codigo;
$this->renderPartial('insumosporpedir',array('ver'=>'1'),FALSE,TRUE);
//Yii::app()->end();
//echo $_POST['data1'];//CHtml::encode(print_r("hola", true));
}
}
public function actionCancelar()
{
unset(Yii::app()->session['pedido-codigo']);
$this->renderPartial('insumosporpedir',array('ver'=>'0'),FALSE,TRUE);
}
public function actionQuitar()
{
if(isset($_POST['dato']))
{
$codigo= Yii::app()->session['pedido-codigo'];
$compara=$_POST['dato'];
foreach ($codigo as $subkey => $subarray)
{
if($subarray['contador']==$compara)
{
unset($codigo[$subkey]);
//echo $codigo[$subkey];
}
}
$ver=1;
if(count($codigo)>0)
{
Yii::app()->session['pedido-codigo']=$codigo;
}
else
{
unset(Yii::app()->session['pedido-codigo']);
$ver=0;
}
//$this->layout='';
$this->renderPartial('insumosporpedir',array('ver'=>$ver),false,true);
//Yii::app()->end();
}
thank you!

I found the problem. the problem wasnt the unset method, it was in the view where I showed the values in the array. insted of using
while($i<$contado)
{
?>
<tr>
<td align="left"><?php echo CHtml::ajaxLink('Quitar', Yii::app()->createUrl('pedidos/quitar'),array('update'=>'#req_res02','type'=>'POST','data'=>array('dato'=>$codigo[$i]['contador'])),array('id'=>'quitar-'. uniqid())); ?></td>
<td align="left"><?php echo $codigo[$i]['contador']; ?></td>
<td align="left"><?php echo $codigo[$i]['insumo']; ?></td>
<td align="left"><?php echo $codigo[$i]['cantidad']; ?></td>
<td align="left"><?php echo $codigo[$i]['observaciones']; ?></td>
</tr>
<?php
$i++;
}
I replaced it with
foreach ($codigo as $key => $value)
{
?>
<tr>
<td align="left"><?php echo CHtml::ajaxLink('Quitar', Yii::app()->createUrl('pedidos/quitar'),array('update'=>'#req_res02','type'=>'POST','data'=>array('dato'=>$value['contador'])),array('id'=>'quitar-'. uniqid())); ?></td>
<td align="left"><?php echo $value['codigo']; ?></td>
<td align="left"><?php echo $value['insumo']; ?></td>
<td align="left"><?php echo $value['cantidad']; ?></td>
<td align="left"><?php echo $value['observaciones']; ?></td>
</tr>
<?php
}
the error occurred because I lost the continuity in the keys everytime I delete a middle array

Related

How to retrieve imploded images path in database to view in code igniter

I am trying to save the multiple images path in database and upload images in root's upload/images[directory]. I have done it and its working. Images name are saved in database and and the image files are being uploaded. I just did save the images name by imploding. Now I need to explode that image in view. How can i do that? I have tried the following code in view and its not working.
<?php foreach ($products as $p): ?>
<tr>
<td><?php echo $p['id']; ?></td>
<td><?php echo $p['product_name']; ?></td>
<td><?php echo $p['product_price']; ?></td>
<td><?php echo $p['produce_description']; ?></td>
<!-- <td><?php echo $p['picture']; ?> </td> -->
<td><img src="<?php echo base_url('uploads/images/').explode('|',$p['picture']);?>" /> </td>
<td>
View |
Edit |
Delete
</td>
</tr>
It throws this error:
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: views/dashboard.php
Line Number: 47
and this is my line 47:
<td><img src="<?php echo base_url('uploads/images/').explode('|',$p['picture']);?>" /> </td>
Incase there is mistake in my image upload function, here is my code for it:
public function set_product($id=0)
{
#code
// if($this->input->post('userSubmit')){
$picture=array();
$count=count($_FILES['picture']['name']);
//Check whether user upload picture
if(!empty($_FILES['picture']['name'])){
foreach($_FILES as $value)
{
for($s=0; $s<=$count-1; $s++)
{
$_FILES['picture']['name']=$value['name'][$s];
$_FILES['picture']['type'] = $value['type'][$s];
$_FILES['picture']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['picture']['error'] = $value['error'][$s];
$_FILES['picture']['size'] = $value['size'][$s];
$config['upload_path'] = 'uploads/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['file_name'] = $_FILES['picture']['name'];
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
// print_r($value['name'][$s]);exit;
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture[] = $uploadData['file_name'];
}
else{
$picture = '';
}
}
}
}//end of first if
else{
$picture = '';
}
$data=array(
'product_name'=>$this->input->post('product_name'),
'produce_description'=>$this->input->post('produce_description'),
'product_price'=>$this->input->post('product_price'),
'picture'=>implode('|',$picture)
);
if ($id==0)
{
return $this->db->insert('products',$data);
}
else {
$this->db->where('id',$id);
return $this->db->update('products',$data);
}
}
And this is my model function for getting data:
public function get_product()
{
#code
$query=$this->db->get('products');
return $query->result_array();
}
Any kind of help are highly appreciated. Thank you.
You should try something like this
<?php foreach ($products as $p): ?>
<?php
// explode images into a variable/array
$images=explode('|',$p['picture']);
?>
<tr>
<td><?php echo $p['id']; ?></td>
<td><?php echo $p['product_name']; ?></td>
<td><?php echo $p['product_price']; ?></td>
<td><?php echo $p['produce_description']; ?></td>
<!-- <td><?php echo $p['picture']; ?> </td> -->
<td><img src="<?php echo base_url('uploads/images/').$images[0];?>" /> </td>
<td>
View |
Edit |
Delete
</td>
</tr>
Edit
I will give you an example from a code in production at this link
<div class="aa-properties-details-img" style="margin-bottom: 25px;">
<?php
$property[0]['images']=explode(',',$property[0]['img']);
if(count($property[0]['images'])>0){
for($i=0;$i<count($property[0]['images']);$i++)
{ ?>
<img src="<?php echo base_url().'img/'.$property[0]['images'][$i]?>" alt="img">
<?php }
}else{
?>
<img src="<?php echo base_url().'img/no-image.jpg'?>" alt="img">
<?php
}
?>
</div>
Try this:
<?php foreach ($products as $p): ?>
<tr>
<td><?php echo $p['id']; ?></td>
<td><?php echo $p['product_name']; ?></td>
<td><?php echo $p['product_price']; ?></td>
<td><?php echo $p['produce_description']; ?></td>
<td>
<?php $images=explode('|',$p['picture']);
foreach($images as $image) {
?>
<img src="<?php echo base_url('uploads/images/').$image; ?>" width="50" height="50" />
<?php } ?>
</td>
<td>
View |
Edit |
Delete
</td>
</tr>

How to display data from query - one to many relationship between db tables

I'm trying to display data from query but I can't show it as it should.
My tables in database are: ordersheader and orderitems. It's one to many relationship between them. One ordersheader have many orderitems. They are joined ON idOrder. One idOrder in ordersheader corresponds to many rows in orderitems.
I have to show all orders for current date and to show all orderitems for each idOrder. It should look like this for all orders:
http://prntscr.com/7lwoan
First row is order - it has to be displayed all orderitems for this order and when you click Details it has to be shown each orderitem on separate row.
Now, as I used code below, each orderitem is shown on separate row. How to make it looks like the above link? Thanks!
My model is:
function getOrders(){
$date = new DateTime("now");
$curr_date = $date->format('Y-m-d ');
$this->db->select('ordersheader.*,customer.name,orderitems.*');
$this->db->from('ordersheader');
$this->db->join('orderitems', 'orderitems.idOrder = ordersheader.idOrder');
$this->db->join('customer', 'customer.idCustomer = ordersheader.idCustomer');
$this->db->where('DATE(orderDueDate)', $curr_date);
$query = $this->db->get();
return $query->result();
}
My view is:
<?php
if($orderlist){
foreach($orderlist as $row) {
?> <tr class="overview">
<td><?php echo $row->idOrder; ?></td>
<td class="text-center"><img src="<?= base_url();?>/assets/images/tick.png"></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->eggSize; ?></td>
<td><?php echo $row->quantity; ?></td>
<td>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 60%;">
60%
</div>
</div>
</td>
<td>18:00</td>
<td><button type="button" class="btn btn-link btn-xs view-full-order">Full</button></td>
</tr>
<tr class="full hide">
<td></td>
<td></td>
<td></td>
<td><?php echo $row->eggSize; ?></td>
<td><?php echo $row->quantity; ?></td>
<td>
<div class="progress">
<div class="progress-bar progress-bar-info" role="progressbar" style="width: <?php echo $rand; ?>%;">
<?php echo $rand; ?>%
</div>
</div>
</td>
<td>14:00</td>
<td></td>
</tr>
<?php } } ?>
</tbody></table>
Edited: I made it with group_concat and explode. But now, problem is that for each idOrder I should calculate average rand (this is the value of progress bar) of all orderitems. This should be for each order - avegare sum of orderitems. Now, it's not calculated correct.
It now looks like that:
http://prntscr.com/7mu0k3
This row where is Billa should be average of the next 2 rows.
My view is:
<tbody class="client">
<?php
if ($orderlist) {
foreach ($orderlist as $row) {
$i = 0;
?> <tr class="overview">
<td><?php echo $row->idOrder; ?></td>
<td class="text-center">
<?php
$s = $row->eggSize;
$egg_size_array = explode(",", $row->eggSize);
$quantity_array = explode(",", $row->quantity);
if (!empty($egg_size_array))
foreach ($egg_size_array as $key => $value) {
$rand[$key] = rand(1, 100);
$random_hour[$key] = rand(01, 24);
}
?>
</td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->eggSize; ?></td>
<td><?php
$s = $row->quantity;
$s = explode(',', $s);
echo array_sum($s);
print_r($rand); echo "<br>";print_r(array_sum($rand)); echo "<br>"; print_r(count($egg_size_array));
?></td>
<td>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: <?php
echo array_sum($rand)/ count($egg_size_array); ?>%;">
<?php echo array_sum($rand)/ count($egg_size_array); echo "%"; ?>
</div>
</div>
</td>
<td><?php echo max($random_hour); echo " ч."; ?></td>
<td><button type="button" class="btn btn-link btn-xs view-full-order">
<?php echo lang('details'); ?> </button></td>
</tr>
<?php
if (!empty($egg_size_array))
foreach ($egg_size_array as $key => $value) {
// $rand = rand(1, 100);
//$random_hour = rand(01, 24);
?>
<tr class="full hide">
<td></td>
<td></td>
<td></td>
<td>
<?php echo $value; ?></td>
<td><?php echo $quantity_array[$key]; ?></td>
<td>
<div class="progress">
<div class="progress-bar progress-bar-info" role="progressbar" style="width: <?php echo $rand[$key]; ?>%;">
<?php echo $rand[$key]; ?>%
</div>
</div>
</td>
<td><?php echo $random_hour[$key] . ' ч.' ?></td>
<td></td>
</tr>
<?php
}
?><?php
}
}
?>
</tbody></table>
My model is:
function getOrders(){
$date = new DateTime("now");
$curr_date = $date->format('Y-m-d');
$this->db->select('orderitems.eggSize as size');
$this->db->select('ordersheader.*,customer.name,GROUP_CONCAT(orderitems.itemNumber) as itemNumber');
$this->db->select('ordersheader.*,customer.name,ordersheader.*,customer.name,GROUP_CONCAT(orderitems.quantity ) as quantity ');
$this->db->select('ordersheader.*,customer.name,ordersheader.*,customer.name,GROUP_CONCAT(orderitems.unitPrice) as unitPrice');
$this->db->select('ordersheader.*,customer.name,ordersheader.*,customer.name,GROUP_CONCAT(orderitems.eggSize ) as eggSize');
$this->db->from('ordersheader');
$this->db->join('orderitems', 'orderitems.idOrder = ordersheader.idOrder');
$this->db->join('customer', 'customer.idCustomer = ordersheader.idCustomer');
$this->db->where('DATE(orderDueDate)', $curr_date);
$this->db->group_by('orderitems.idOrder');
$query = $this->db->get();
return $query->result();
}
You should create a function to return order children.
function GetItems($idOrder)
{
return $this->db->get_where("orderitems", "idOrder" => $idOrder)->array_result();
}
After that, you will remove the JOIN with the orderitems table. And then you should get the array_result of your query and iterate with it by foreach and attach the children in your collection like this:
$curr_date = $date->format('Y-m-d ');
$this->db->select('ordersheader.*,customer.name');
$this->db->from('ordersheader');
$this->db->join('customer', 'customer.idCustomer = ordersheader.idCustomer');
$this->db->where('DATE(orderDueDate)', $curr_date);
$query = $this->db->get()->array_result();
$index = 0;
foreach($query as $item)
{
$query[$index]["children"] = GetItems($item->idOrder);
$index++;
}
I've created a mockup in a fiddle to show you an example: http://codepad.org/LfjQJQCP

Display data from a query - I can't display it properly

I'm trying to show result from a query but I can't display it as it should.
I have two tables - ordersheader and orderitems.
ordersheader is the table for orders. It's structure is:
idOrder,idCustomer,createdDate,orderDueDate.
My table 'orderitems' contains separate orderitems for each order .It has the following structure:
orderitem_id,idOrder,item_number,eggSize,quantity,price.
These two tables are joined ON idOrder. One row from ordersheader corresponds to many rows in orderitems because one order could have many orderitems in it.
My problem is that I can't show them properly. It has to be shown like this:
http://prntscr.com/7lwnz7
and when you click Details it should look like that:
http://prntscr.com/7lwoan
Now,they are shown each orderitem on new line like this:
http://prntscr.com/7lworg
I have to make result from each idOrder to be displayed in one row.
Should I use inner loop and how to do that?
My model is:
<?php
function getOrders(){
$date = new DateTime("now");
$curr_date = $date->format('Y-m-d');
$this->db->select('ordersheader.*,customer.name,orderitems.*');
$this->db->from('ordersheader');
$this->db->join('orderitems', 'orderitems.idOrder = ordersheader.idOrder');
$this->db->join('customer', 'customer.idCustomer = ordersheader.idCustomer');
$this->db->where('DATE(orderDueDate)', $curr_date);
$query = $this->db->get();
return $query->result();
My view is:
<?php
if($orderlist){
foreach($orderlist as $row) {
?> <tr class="overview">
<td><?php echo $row->idOrder; ?></td>
<td class="text-center"><img src="<?= base_url();?>/assets/images/tick.png"></td>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->eggSize; ?></td>
<td><?php echo $row->quantity; ?></td>
<td>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 60%;">
60%
</div>
</div>
</td>
<td>18:00</td>
<td><button type="button" class="btn btn-link btn-xs view-full-order">Full</button></td>
</tr> <?php for($i=0;$i<count($row->eggSize); $i++) { ?>
<tr class="full hide">
<td></td>
<td></td>
<td></td>
<td><?php echo $row->eggSize; ?></td>
<td><?php echo $row->quantity; ?></td>
<td>
<div class="progress">
<div class="progress-bar progress-bar-info" role="progressbar" style="width: <?php echo $rand; ?>%;">
<?php echo $rand; ?>%
</div>
</div>
</td>
<td>14:00</td>
<td></td>
</tr><?php } ?>
<?php } } ?>
</tbody></table>
<?php
function getOrders(){
$date = new DateTime("now");
$curr_date = $date->format('Y-m-d');
$this->db->select('ordersheader.*,customer.name,GROUP_CONCAT(orderitems.item_number SEPARATOR ",") as item_number');
$this->db->select('ordersheader.*,customer.name,GROUP_CONCAT(orderitems.priceSEPARATOR ",") as price');
$this->db->select('ordersheader.*,customer.name,GROUP_CONCAT(orderitems.eggSize SEPARATOR ",") as eggSize');
$this->db->from('ordersheader');
$this->db->join('orderitems', 'orderitems.idOrder = ordersheader.idOrder');
$this->db->join('customer', 'customer.idCustomer = ordersheader.idCustomer');
$this->db->where('DATE(orderDueDate)', $curr_date);
$query = $this->db->get();
return $query->result();
?>

Codeigniter include file variables come null

I have a foreach inside a table that loads a file with a row <tr>.
That problem is that all the variables come null and I've already tried to send the variable with the load as you can see in the next code line but no success:
$this->load->view('pedidos/tarefas/tarefa_table', $task);
This is my table:
<table>
<thead>
<tr>
<th>ID</th>
<th>Utilizador</th>
<th>Entidade</th>
<th>Descrição</th>
<th>Data Limite</th>
<th>Estado</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<?php
foreach ($tasks as $task) {
$this->load->view('pedidos/tarefas/tarefa_table', $task);
}
?>
</tbody>
</table>
This is the file I'm including in the load->view:
tarefa_table.php
<tr class="odd gradeX">
<td><?php print_r($task->id); ?></td>
<td><?php echo substr($task->user->name, 0, 20); if(intval(strlen($task->user->name)>=20))echo ".."; ?></td>
<td><?php echo substr($task->entidade->name, 0, 20); if(intval(strlen($task->entidade->name)>=20))echo ".."; ?></td>
<td><?php echo substr($task->descricao, 0, 30); if(intval(strlen($task->descricao)>=30))echo ".."; ?></td>
<td style="<?php
if ($task->status_id <= 2 || $task->status_id >= 6) {
if (date('Y-m-d', strtotime($task->data_fim)) == date('Y-m-d')) {
echo "color: orange";
} elseif (date('Y-m-d', strtotime($task->data_fim)) < date('Y-m-d')) {
echo "color: red";
}else{
echo "color:#274156";
}
} ?>"><?php echo date('d-m-Y', strtotime($task->data_fim)) ?>
</td>
<td><?php
if($task->status_id <= 2 && date('Y-m-d', strtotime($task->data_fim)) < date('Y-m-d')){
echo "Atraso";
}else{
switch ($task->status_id) {
case 1: echo "Ativo"; break;
case 2: echo "Atraso"; break;
case 3: echo "Pendente"; break;
case 4: echo "Concluído"; break;
case 5: echo "Cancelado"; break;
case 6: echo "Ativo"; break;
case 7: echo "Atraso"; break;
default: echo "Não Definido"; break;
}}?>
</td>
<td class="center">
<a href="<?php echo base_url() . 'pedidos/view_task/' . $task->id ?>" title="Ver" class="tip">
<button class="btn btn-link btn-mini"><span class="icon16 icomoon-icon-eye"></button>
</a>
<a href="<?php echo base_url() . 'pedidos/edit_task/' . $task->id ?>" title="Editar" class="tip">
<button class="btn btn-link btn-mini"><span class="icon16 icomoon-icon-pencil-5"></button>
</a>
<!--<a href="<?php //echo base_url() . 'pedidos/deletetask/' . $task->id ?>" class="confirm-delete tip" title="Apagar">
<button class="btn btn-link btn-mini"><span class="icon16 typ-icon-trashcan red"></button>
</a>-->
</td>
</tr>
why not load a view in controller , loop through your data and append in your variable like
$tablecontent and just echo it in your first view
//controller
function your_fucntion(){
$tablecontent="";
foreach ($tasks as $task) {
$tablecontent.=$this->load->view('pedidos/tarefas/tarefa_table', $task,true);
}
$data['tablecontent']=$tablecontent;
$this->load->view('your view path', $data);
}
//view
<table>
<thead>
<tr>
<th>ID</th>
<th>Utilizador</th>
<th>Entidade</th>
<th>Descrição</th>
<th>Data Limite</th>
<th>Estado</th>
<th>Ações</th>
</tr>
</thead>
<tbody>
<?php
echo $tablecontent;
?>
</tbody>
</table>

Displaying serial numbers with query result

I am trying to fetch data from my database and when I display it I want to show serial numbers (Just like a list) , example:
**Serial Number** Name Country
1. John USA
2. Srijon UK
I have tried something with PHP Loops, but I couldn't make it work. Would you please kindly help me? please note that by serial numbers I don't mean values retrieved from database.
Thanks in Advance :)
Here's my Model
//Function To Create All Batch List
function batch_list($perPage,$uri) {
$this->db->select('*');
$this->db->from('batch');
$this->db->join('teacher', 'batch.batchinstructor = teacher.teacherid');
$this->db->order_by('batchid','DESC');
$getData = $this->db->get('', $perPage, $uri);
if($getData->num_rows() > 0)
return $getData->result_array();
else
return null;
}
//End of Function To Create All Batch List
Here's mY Controller
function index(){
$this->load->library('pagination');
$config['base_url'] = base_url().'batchlist/index';
$config['total_rows'] = $this->db->get('batch')->num_rows();
$config['per_page'] = 20;
$config['num_links'] = 20;
$config['full_tag_open'] = '<div class="pagination" align="center">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$this->load->model('mod_batchlist');
$data['records']= $this->mod_batchlist->batch_list($config['per_page']
,$this->uri->segment(3));
$data['main_content']='view_batchlist';
$this->load->view('includes/template',$data);
}
Here's My View
<?php if(count($records) > 0) { ?>
<table id="table1" class="gtable sortable">
<thead>
<tr>
<th>Batch Name</th>
<th>Class</th>
<th>Batch Instructor</th>
<th>Edit/Delete</th>
</tr>
</thead>
<tbody>
<?php foreach ($records as $row){ ?>
<tr>
<td><?php echo $row['batchname'];?> </td>
<td><?php echo $row['class'];?></td>
<td><?php echo $row['teachername'];?></td>
<td> <img src="<?php echo base_url(); ?> support/images/icons/edit.png" alt="Edit" />
<img src="<?php echo base_url(); ?>support/images/icons/cross.png" alt="Delete" />
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
<div class="tablefooter clearfix">
<div class="pagination">
<?php echo $this->pagination->create_links(); ?>
</div>
</div>
<?php if(count($records) > 0) { ?>
<table id="table1" class="gtable sortable">
<thead>
<tr>
<th>Serial</th>
<th>Batch Name</th>
<th>Class</th>
<th>Batch Instructor</th>
<th>Edit/Delete</th>
</tr>
</thead>
<tbody>
<?php $i = $this->uri->segment(3); foreach ($records as $row){ $i++; ?>
<tr>
<td><?php echo $i; ?>.</td>
<td><?php echo $row['batchname'];?> </td>
<td><?php echo $row['class'];?></td>
<td><?php echo $row['teachername'];?></td>
<td> <img src="<?php echo base_url(); ?> support/images/icons/edit.png" alt="Edit" />
<img src="<?php echo base_url(); ?>support/images/icons/cross.png" alt="Delete" />
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
<div class="tablefooter clearfix">
<div class="pagination">
<?php echo $this->pagination->create_links(); ?>
</div>
</div>
In my case the fourth and fifth parameters where page number and rows per page respectively
ie: example.com/category/page/1/10
first page with 10 rows per page.
so in this case just use this before the loop
$i = $this->uri->segment(4)? (
$this->uri->segment(4) + $this->uri->segment(5)? $this->uri->segment(5):0
)
:0;
and from inside the loop just increment the value of i.
foreach ($result_obj as $key => $value)
{
$i++;
...
}
Try this..work like this..1,2,3,4,5
$i = 0
while($condition)
{
echo '<td>'.$i++.'</td>';
}

Resources