Update field using foreach loop in codeigniter not working - php

I have an issue I´m trying to update a field from a column using codeigniter , I display results from database using a foreach loop then I want to add a button called "reactivate" to change the status of that column, the PROBLEM is that it updates all the fields I just want to update the row I´m clicking in but it changes the 'Status' of all the other accounts, I don´t know how to solve this issue. Thanks in advance.
This is my view:
div class='container'>
<h5>Histórico</h5>
<table id='table' class='table'>
<thead>
<tr>
<th>INTERNO</th>
<th>CLABE</th>
<th>FECHA_ALTA</th>
<th>FECHA_BAJA</th>
<th>STATUS</th>
<th>ACCIÓN</th>
</thead>
<tbody>
<?php
foreach ($mos-> result() as $row) {
echo "<tr>";
echo "<td>".$row->Interno;"</td>";
echo "<td>".$row->Clabe;"</td>";
echo "<td>".$row->Fecha_alta;"</td>";
echo "<td>".$row->Fecha_baja;"</td>";
echo "<td>".$row->Status;"</td>";
echo "<td><input type='submit' id='ReActivar' name='ReActivar' class='btn btn-success' value='ReActivar' onclick='return validacion();' disabled><span id='msg'></span></td>";
"</tr>";
}
?>
</tbody>
</table>
</div>
This is my controller:
function decision(){
if (!empty($_POST['actualizar'])) {
$this->validaclabe();
}
if (!empty($_POST['Desactivar'])) {
$this->update_Status();
}
if (!empty($_POST['ReActivar'])) {
$this->update_Status_again();
}
}
function update_Status_again()
{
$this->load->helper('date');
date_default_timezone_set('America/Mexico_City');
$now = date('Y-m-d H:i:s');
$Interno = $this->input->post('Interno');
$Status = $this->input->post('activo');
$data = array(
'Status' => ! empty($Status) ? $Status : 'A',
'Fecha_alta' => $now,
);
//$data['status'] = ! empty($Status) ? $Status : 'I';
if ( ! empty($Interno))
{
$updated = $this->consultas_M->update_Status($Interno, $data);
if($updated)
{
//echo " update successful...";
$this->logueado();
//redirect('index.php/Datos/search2');
}
else
{ echo "update not successful...";}
} else
{ echo "Interno not found ..."; }
}
This is the model:
function muestra_inactivos($Interno)
{ $Status = 'A';
//$Interno = $this->input->get('Interno');
$this->db->select('Interno, Clabe, Fecha_alta, Fecha_baja, Status');
$this->db->where('Status !=', $Status);
$this->db->where('Interno =', $Interno);
$q= $this->db ->get('cuentas');
if($q -> num_rows() >= 0){
return $q;
}else{
return false;
}
}
function update_Status_again($Interno,$data)
{
$this->db->where('Interno', $Interno);
return $this->db->update('cuentas', $data);
if ( $this->db->affected_rows() > 0 )
{
return TRUE;
}
else
{
return FALSE;
}
}
This is also a picture I also don´t know why one button is disabled and the other is not.

Related

codeigniter error loop with page redirect

Hello I have created an update query using a concept that if the id is valid then it should update the data otherwise it will not do so but when any of the conditions meet it redirects and says page is redirecting to the loop why is this happening so ?
Controller
public function confirm() {
if($this->session->userdata('is_logged_in') == true) {
$invc = "#".$this->input->get('id');
if($invc == true) {
$this->data_update->update_trans($invc);
} else {
redirect('home/confirm');
}
} else {
redirect('user/login');
}
}
Here is my model file
public function update_trans($invc_id) {
$get_trans = $this->db->get_where('transaction', array("invc_id" => $invc_id));
$user_id = $get_trans->row()->userid;
$amount = $get_trans->row()->ammount;
if(!empty($user_id)) {
$check = $this->db->get_where('account', array("user_id" => $user_id));
if($check->row()->balance == true) {
$new_amount = ($amount + $check->row()->balance);
$dataupdate = array(
'user_id' => $user_id,
'balance' => $new_amount
);
$this->db->where('id', $user_id);
$this->db->update('account', $dataupdate);
$this->db->where('invc_id', $invc_id);
$this->db->update('transaction', array('status' => 'Confirmed'));
redirect('home/confirm?id='.$invc_id);
} else {
$data1 = array(
'user_id' => $user_id,
'balance' => $amount
);
$this->db->insert('account', $data1);
$this->db->where('invc_id', $invc_id);
$this->db->update('transaction', array('status' => 'Confirmed'));
redirect('home/confirm?id='.$invc_id);
}
} else {
redirect('home/confirm');
}
}
And this is my view file
<?php
require('sidebar.php');
?>
<!-- Body Content -->
<div id="body">
<?php
if($this->input->get('id') == true) {
?>
<div class="msg">
<h4>Your Payment Has been confirmed successfully</h4>
</div>
<?php } else { ?>
<div class="msg">
<h4>Payment Not confirmed</h4>
</div>
<?php } ?>
</div>
<div id="break"> </div>
</div>
I dont know why but it is giving me the same error This webpage has a redirect loop can anyone help me out with this please
In your function its going every time in else part (redirect('home/confirm');) so its showing error. Your function should be like this..
public function confirm() {
if($this->session->userdata('is_logged_in') == true) {
$invc = "#".$this->input->get('id');
if($this->input->get('id')) {
$this->data_update->update_trans($invc);
} else {
redirect('home/confirm');
}
} else {
redirect('user/login');
}
}
Hope this will solve your issue.
Try your confirm() function as like that:
public function confirm()
{
if($this->session->userdata('is_logged_in') == true) {
$id = intval($this->input->get('id'));
$invc = "#".$id;
if($id > 0) {
$this->data_update->update_trans($invc);
} else {
redirect('home/confirm');
}
} else {
redirect('user/login');
}
}
You are expecting this "#".$this->input->get('id') will return you true or false.
And more if still facing same issue, than check what are you getting in $_GET like:
if($this->session->userdata('is_logged_in') == true) {
print_r($_GET); // will return you an array
}

read more function with codeigniter

i am trying to create a readmore function in codeigniter where the readmore link will be linked to a controller which would show all the data about that particular id....i am kind of confused on how to go about it... i tried...
<?php
$research_detail_url = site_url()."/research/research_details";
//echo json_encode($research)
if($research)
{
foreach ($research as $_research) {
$author = $_research->author;
$content = $_research->content;
$dsubmitted = $_research->dsubmitted;
echo "<div class='menu-collapse'> <h5>$author</h5>";
echo "<p>";
echo "<span class='support_text'>$content <span><br />";
echo "<span class='support_text'>$dsubmitted <span><br />";
echo "<a href='$research_detail_url' target='_blank' style='text-decoration:underline; color:#0088cc;'>
read more » </a>";
echo "</p> </div>";
}
}
?>
but i seem not be getting any results...i need help...
and this is my controller function.....
public function research_details($id='')
{
if(!$id)
{
echo "Project Id required";
return;
}
$_result = $this->projects_model->get_project($id);
if($_result)
{// success in fetching data hurray
$result['projects'] = $_result;
$users_ids = $this->users_model->get_user_ids(); //return available user id's
$groups_ids = $this->groups_model->get_group_ids(); //return available group id's
//echo json_encode($users_ids);
//echo json_encode($groups_ids);
$group_record = $this->map_names_to_ids($users_ids , $groups_ids );
$result['group_record'] = $group_record;
//load the view
$this->load->view('__includes__/header');
$this->load->view('__includes__/boostrap_responsive');
$this->load->view('projects/project_panel', $result);
$this->load->view('__includes__/footer_scripts');
$this->load->view('__includes__/wijmo_file_jquery');
$this->load->view('__includes__/footer');
}
else
{
exit("An Error occured in fetching the requested project");
}
}
and this is my model.....
<?php
class research_model extends CI_Model {
function add()
{
$this->db->insert('research',$_POST);
if($this->db->_error_number())
{
return $this->db->_error_number();
}
}
function update($article_id, $data_fields = NULL){
if($data_fields == NULL)
{
$this->db->where("article_id =".$article_id);
$this->db->update('research',$_POST);
}
else
{
$this->db->where("article_id =".$article_id);
$this->db->update('research',$data_fields);
}
$is_error = $this->db->_error_number();
if($is_error){
echo $is_error;
}
return TRUE;
}
function delete($id){
$this->db->where("article_id =".$id);
return $this->db->delete('research');
}
//return the research with this id
function get_research($id){
$this->db->where("article_id =".$id);
$query = $this->db->get('research');
if ($query->num_rows() > 0){
return $query->row_array();
}
else
echo $this->db->_error_message();
return FALSE;
}
//return the available research in the table
function get_research_all(){
$query = $this->db->get('research');
if ($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
$result[] = $row;
}
return $result;
}
}
}
and my entire controller.....
<?php
class Research extends Public_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('research_model');
}
function index()
{
if($this->ion_auth->is_admin())
{
$result = $this->research_model->get_research_all();
$data = array(
'main_content' => 'research/index',
'research' => $result
);
$this->load->view("loader", $data);
}
else
{
redirect('home');
}
}//END INDEX
// public view
function current()
{
$result = $this->research_model->get_research_all();
$data = array('research' => $result);
$this->load->view('__includes__/header');
$this->load->view('__includes__/navbar');
$this->load->view('research/current', $data);
$this->load->view('__includes__/footer');
}
function add()
{
if($this->ion_auth->is_admin())
{
$this->load->view("loader",array('main_content'=>"research/add_research"));
}
}//END ADD
function edit($id='')
{
if(! $id)
{
echo "research Id required";
return;
}
$result = $this->research_model->get_research($id);
if( ! $result)
{
echo "Nothing to edit";
return;
}
$result['main_content'] = "research/add_research";
$this->load->view("loader",$result);
}//END EDIT
function delete($id='')
{
if(! $id)
{
echo "Id required";
return;
}
$this->research_model->delete($id);
$this->get_research();
}//END DELETE
function submit($id='')
{
//validate form [perform validation server-side to make sure of fields]
$this->load->library('form_validation');
$this->form_validation->set_rules('author', 'Author', 'trim|required|min_length[4]');
if ($this->form_validation->run() == FALSE){
//ajax data array
$data = array(
'server_validation' => validation_errors()
);
echo str_replace('\\/', '/', json_encode($data));
}
else{
if($id){
$result = $this->research_model->update($id);
$content = "article has been UPDATED successfully";
//$retArr["content"] = $content;
//echo json_encode($retArr);
}
else{
$result = $this->research_model->add();
$content = "article has been CREATED successfully";
//$retArr["content"] = $content;
//echo json_encode($retArr);
}
//if duplicate key
if($result == 1062){
//ajax data array
$data = array();
$data['is_valid'] = 0;
echo json_encode($data);
}else{
//ajax data array
$data = array(
'is_valid' => 1,
'content' => $content
);
echo json_encode($data);
}
}//end ELSE form valid
}//END SUBMIT
public function research_details($id='')
{
if(!$id)
{
echo "Project Id required";
return;
}
$_result = $this->research_model->get_research($id);
if($_result)
{// success in fetching data hurray
$result['article'] = $_result;
//load the view
$this->load->view('__includes__/header');
$this->load->view('__includes__/boostrap_responsive');
$this->load->view('research/research_details', $Aresult);
$this->load->view('__includes__/footer_scripts');
$this->load->view('__includes__/wijmo_file_jquery');
$this->load->view('__includes__/footer');
}
else
{
exit("An Error occured in fetching the requested project");
}
}//END EDIT
}
?>
my public controller
<?php
abstract class Public_Controller extends CI_Controller
{
public $about_data;
function __construct()
{
parent::__construct();
//Making This variable availale for the whole site
$this->load->model('about_model');
$this->load->model('captcha_model');
//get your data
$this->about_data = $this->about_model->get_abouts();
}
}
?>
I see a couple of problems:
In your view, you are not closing the span tags. You need
</span>
In your view, you are creating the link, but you are not
including an ID, which you need in your controller. What I mean by this is the following:
First,you create this $research_detail_url = site_url()."/research/research_details";.
Then echo "<a href='$research_detail_url' target='_blank' style=''>read more</a>";
As you can see, your URL does not have an ID when created. What you should do is something like this: $research_detail_url = site_url()."/research/research_details/31"; where 31 is a random ID. You need to come up with the right ID needed in order to pass it to your controller. Your controller is currently assigning a blank ID since none is being passed which is why you end up with a result of "Project Id required"

PHP Update in codeigniter

I am trying to write a function to insert, update, and delete data. I can insert data, but can't update the data. The problem is I can't pass id value to my updateform.
Controller:
function update($id = 0){
$this->load->helper('form');
$this->load->helper('html');
$this->load->model('employees_model');
if($this->input->post('upsubmit')){
echo '<pre>';print_r($id);echo '</pre>';
exit();
if($this->input->post('eid')){
$this->employees_model->entry_update();
}
}
$data = $this->employees_model->general();
if((int)$id > 0){
$query =this->employees_model->get($id);
$data['txt_id']['value'] = $query['eid'];
$data['txt_name']['value'] = $query['ename'];
$data['txt_salary']['value'] = $query['esalary'];
$data['txt_emailid']['value'] = $query['eemailid'];
}
$this->load->view('employees_update',$data);
}
Model:
function general(){
$data['base'] = $this->config->item('base_url');
$data['css'] = $this->config->item('css');
$data['id']['value'] = 'eid';
$data['name'] = 'txt_name';
$data['salary'] = 'txt_salary';
$data['emailId'] = 'txt_email';
return $data;
}
function entry_update($id){
$this->load->database();
echo '<pre>';print_r($id);echo '</pre>';
exit();
$data = array(
'ename'=>$this->input->post('txt_name'),
'esalary'=>$this->input->post('txt_salary'),
'eemailid'=>$this->input->post('txt_email'),
);
echo '<pre>';print_r($data);echo '</pre>';
exit();
$this->db->where('eid',$this->input->post($data));
$this->db->update('employee',$data);
//echo '<pre>';print_r($data);echo '</pre>';
echo "Updated successfully";
}
function get($id)
{
$this->load->database();
$query = $this->db->get_where('employee',array('eid'=>$id));
return $query->row_array();
}
Please suggest how to pass Select id values to update form page in views section.
Here is my working sample code. Hopes it helps.
controller
//I am using update from to preload data
function update_form($id)
{
$query=$this->product_model->get($id);
$data['id']=$query['id'];
$data['name']=$query['name'];
$data['price']=$query['price'];
$this->load->view('products/update_product',$data);
}
function update()
{
$this->product_model->save();
redirect('products/index');
}
Model
function get($id=0)
{
if($id==0)
{
$query=$this->db->get('product');
return $query->result_array();
}
else
{
$this->db->where('id',$id);
$query=$this->db->get('product');
return $query->row_array();
}
}
// if **id** is greater than zero mean update, no **id** mean insert
function save()
{
$id=$this->input->post('id');
$name=$this->input->post('name');
$price=$this->input->post('price');
$data=array
(
'name'=>$name,
'price'=>$price
);
if($id>0)
{
$this->db->where('id',$id);
$this->db->update('product',$data);
}
else
{
$this->db->insert('product',$data);
}
}
}
View (view/products/update_product.php)
<?php echo form_open('products/save');?> //form_open('controller_name/function_name');
<?php echo form_hidden('id',$id);?>
<?php echo form_input('name',$name,'placeholder="enter doctor name"');?><br>
<?php echo form_input('price',$pricce,'placeholder="enter doctor phone number"');?><br>
<?php echo form_submit('','Update');?>
<?php echo form_close();?>
id play vita role in updating , you shouldn't include it in View as Hidden Field
At first you created function with parameter $id. But when you call the function without parameter.
change this line
in Controller change this line
$this->employees_model->entry_update();
to
$this->employees_model->entry_update($this->input->post('eid'));
In Model Change this line:
$this->db->where('eid',$this->input->post($data))
to
$this->db->where('eid',$this->input->post('eid'));
Change your update function like as below:
function update($id = 0){
$this->load->helper('form');
$this->load->helper('html');
$this->load->model('employees_model');
if($this->input->post('upsubmit')){
$id= $this->input->post('eid');
if($this->input->post('eid')){
$this->employees_model->entry_update();
}
}
$data = $this->employees_model->general();
if((int)$id > 0){
$query =this->employees_model->get($id);
$data['txt_id']['value'] = $query['eid'];
$data['txt_name']['value'] = $query['ename'];
$data['txt_salary']['value'] = $query['esalary'];
$data['txt_emailid']['value'] = $query['eemailid'];
}
$this->load->view('employees_update',$data);
}

article post not updating in codeigniter blog

I am new in codeigniter. I build a cms with codeigniter for blog. But when i want edit a article post and want to save it, it create new one post not update old post which i edited.
Please help me.
My Article Edit crontroller:
public function edit ($id = NULL)
{
// Fetch a article or set a new one
if ($id) {
$this->data['article'] = $this->article_m->get($id);
count($this->data['article']) || $this->data['errors'][] = 'article could not be found';
}
else {
$this->data['article'] = $this->article_m->get_new();
}
// categories for dropdown
$this->data['all_categories'] = $this->article_m->join();
// Set up the form
$rules = $this->article_m->rules;
$this->form_validation->set_rules($rules);
// Process the form
if ($this->form_validation->run() == TRUE) {
$data = $this->article_m->array_from_post(array(
'title',
'extra_title',
'slug',
'image',
'category_id',
'body',
'pubdate'
));
$this->article_m->save($data, $id);
redirect('admin/article');
}
// Load the view
$this->data['subview'] = 'admin/article/edit';
$this->load->view('admin/_layout_main', $this->data);
}
My Models:
public function array_from_post($fields){
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
public function get($id = NULL, $single = FALSE){
if ($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
}
elseif($single == TRUE) {
$method = 'row';
}
else {
$method = 'result';
}
if (!count($this->db->ar_orderby)) {
$this->db->order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE){
$this->db->where($where);
return $this->get(NULL, $single);
}
public function save($data, $id = NULL){
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
}
// Update
else {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
public function get_new ()
{
$article = new stdClass();
$article->title = '';
$article->extra_title = '';
$article->slug = '';
$article->image = '';
$article->category_id = '';
$article->body = '';
$article->pubdate = date('Y-m-d');
return $article;
}
public function join()
{
$this->db->select('name,categories.id as category_id');
$this->db->from($this->_table_name);
$this->db->join('categories', 'categories.id = category_id','right');
$Q = $this->db->get();
if ($Q->num_rows() > 0){
foreach ($Q->result_array() as $row){
$data[$row['category_id']] = $row['name'];
}
}
$Q->free_result();
return $data;
}
My View:
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('admin/article/edit'); ?>
<table class="table">
<tr>
<td>Publication date</td>
<td><?php echo form_input('pubdate', set_value('pubdate', $article->pubdate), 'class="datepicker"'); ?></td>
</tr>
<tr>
<td>Category</td>
<td><?php
$js = 'id="category_id" onChange="some function();"';
echo form_dropdown('category_id', $all_categories, set_value('category_id', $article->category_id), $js); ?></td>
</tr>
<tr>
<td>Title</td>
<td><?php echo form_input('title', set_value('title', $article->title)); ?></td>
</tr>
<tr>
<td>Extra Title (Optional)</td>
<td><?php echo form_input('extra_title', set_value('extra_title', $article->extra_title)); ?></td>
</tr>
<tr>
<td>Slug</td>
<td><?php echo form_input('slug', set_value('slug', $article->slug)); ?></td>
</tr>
<tr>
<td>Upload Image</td>
<td>
<div class="input-append">
<?php echo form_input('image', set_value('image', $article->image),'id="fieldID"'); ?>
Select
</div>
</td>
</tr>
<tr>
<td>Body</td>
<td><?php echo form_textarea('body', set_value('body', $article->body), 'class="tinymce"'); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?></td>
</tr>
</table>
<?php echo form_close();?>
Please Help Me.
You have to pass the id to the controller. In your view you are telling the form to submit to
article/edit but not the id.
<?php echo validation_errors(); ?>
<?php echo form_open_multipart('admin/article/edit/'.$article->id); ?>
...
You'll probably get some warnings if $article is not set, so you may want to put in some checks for when you're adding a new item.

Codeigniter view shows 0 record

i've insert 5 rows into ms_kategori_material table, and made some model here
function read()
{
$query = $this->db->get('ms_kategori_material');
if($query->num_rows()>0)
{
foreach ($query->result_array() as $value) {
echo $value['Kode_Kategori_Material_Jasa'];
echo $value['Nama_Material_Jasa'];
}
return $value;
}
else
{
return null;
}
}
and controllers
function index()
{
$data['kirim'] = $this->m_kategorimaterial->read();
echo $data; //returns KKMJ001batuKKMJ002batuKKMJ003batuKKMJ004batuKKMJ005batuArray
$this->load->view('v/vkategorimaterial',$data);
}
and the views
<?php
if ( !empty($kirim) ) {
$no = 1;
foreach ($kirim as $row) { ?>
<tr id="row">
<td id="no"><?php echo $no;?></td>
<td id="judul"><?php echo $row->Kode_Kategori_Material_Jasa;?></td>
<td id="kategori"><?php echo $row->Nama_Material_Jasa;?></td>
</tr> ?>
<?php
$no++;
}
} else { ?>
<tr id="row">
<td colspan="6" align="center">Data tidak ditemukan</td>
//the screen shows 'data tidak ditemukan' </tr>
<?php
}
?>
this is so confusing, since i can see the data in the controller, then pass them into the views, views said no data received
In your model
if($query->num_rows()>0)
{
foreach ($query->result_array() as $value) {
echo $value['Kode_Kategori_Material_Jasa'];
echo $value['Nama_Material_Jasa'];
}
return $value;
}
it's wrong, it should be
if($query->num_rows()>0)
{
return $query->result();
}
and in your controller you should have
function index()
{
$this->load->model('m_kategorimaterial'); // load it if it's not autoloaded
$data['kirim'] = $this->m_kategorimaterial->read();
$this->load->view('v/vkategorimaterial',$data);
}
Just reread your code. You're returning $value but never populating it. See below.
{
$query = $this->db->get('ms_kategori_material');
if($query->num_rows()>0)
{
$value = $query->result(); // or result_array() but you're using it as an object in the view not an array.
return $value;
}
else
{
return null;
}
}
You are actually not returning the results in your model,
replace
foreach ($query->result_array() as $value)
{
echo $value['Kode_Kategori_Material_Jasa'];
echo $value['Nama_Material_Jasa'];
}
with
if($query->num_rows()>0)
{
return $query->result();
}

Categories