Unable to Update and delete in CodeIgniter? - php

I'm new in CodeIgniter, just watched the tutorial on youtube and followed the steps.
I can't edit or delete records of my database. I can insert or fetch records, but update and delete functions always return error. Here is my code
Controller:
function __construct()
{
parent::__construct();
$this->load->model('Danhmuc_model');
}
function xoadm()
{
$id = $this->uri->segment(5);
$this->Danhmuc_model->delete($id);
$this->session->set_flashdata('mess',' Đã xóa thành công');
redirect(admin_url('danhmuc/xemdm'));
}
function suadm()
{
$data = array();
$id = $this->uri->segment(5);
$row = $this->Danhmuc_model->get_info($id);
if($this->input->post())
{
$this->form_validation->set_rules('ten_dm',"Tên danh mục",'required');
if($this->form_validation->run())
{
$tendm = $this->input->post('ten_dm');
$input = array('ten_dm'=>$tendm);
$this->Danhmuc_model->update($id,$input);
$this->session->set_flashdata('mess',' Đã sửa thành công');
}
}
$data['row'] = $row;
$data['temp'] = 'admin/danhmuc/suadm';
$this->load->view('admin/index',$data);
}
Model:
function update($id, $data)
{
if (!$id)
{
return FALSE;
}
$where = array();
$where[$this->key] = $id;
$this->update_rule($where, $data);
return TRUE;
}
/**
* Xoa row tu id
* $id : gia tri cua khoa chinh
*/
function delete($id)
{
if (!$id)
{
return FALSE;
}
//neu la so
if(is_numeric($id))
{
$where = array($this->key => $id);
}else
{
//xoa nhieu row
//$id = 1,2,3...
$where = $this->key . " IN (".$id.") ";
}
$this->del_rule($where);
return TRUE;
}
View:
Edit view:
<td>
<input name="title" class="form-control" type="text" value="<?php echo $row['ten_dm'] ?>">
</td>
If I use this value="<?php echo $row['ten_dm'] ?>", the text box doesn't appear the category's title (I'm inserting and editing categories)
https://imgur.com/lW7FeDA
https://imgur.com/Z6TjnhL
But if I use this value="<?php echo $row->ten_dm ?>", error with this message
A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object
Filename: danhmuc/suadm.php
Line Number: 13
I can't understand where is the error, please help me. Thanks in advance.

Related

How to update the existing values

I am creating an API where I'm inserting product_id, Product_Size, quantity, product_name in an array called product-info.
Now I want to update the other values when product id is already existing.
my code for insertion in controller:
if(!empty($product_info1)){
foreach ($product_info1 as $value) {
$product_id = isset($value->product_id) ? $value->product_id : 0;
$Product_Size = isset($value->Product_Size) ? $value->Product_Size : 0;
$quantity = isset($value->quantity) ? $value->quantity : 0;
$product_name = isset($value->product_name) ? $value->product_name : 0;
if( $ok = 1)
$this->api_details_model->productinventory_track($product_id,$Product_Size,$quantity,$product_name);
{
$api_status="true";
$api_message="Done";
}
// $this->api_details_model->checkProductid($product_id);
}
}
model:
function productinventory_track($product_id,$Product_Size='',$quantity='',$product_name='')
{
if($product_id>=0)
{
$data = array('product_name'=>$product_name,'size_id'=>$Product_Size,'stock_count'=>$quantity,'product_id'=>$product_id);
if($this->db->insert('product_inventory', $data)){ return true; }else{ return false; }
}
please tell me the code for update
Controller:
$productInfo = $this->db->api_details_model->get($product_id);
$productArray['product_name'] = 'yourValue';
$productArray['size_id'] = 'yourValue';
$productArray['stock_count'] = 'yourValue';
// Means that there is no product with that ID in the database
if($productInfo == null)
$this->db->api_details_model->add($productArray);
// It was found an ID in the database
else
$this->db->api_details_model->edit($product_id, $productArray);
Functions in model:
public function add($data)
{
$this->db->insert('product_inventory', $data);
}
public function edit($id, $data)
{
$this->db->where('id', $id)
->update('product_inventory', $data);
}
public function get($id)
{
$this->db->where('id', $id);
return $this->db->get('product_inventory')->row();
}

How to delete image from database codeigniter?

This my controller:
public function doDelete($id_jeans)
{
$where = array("id_jeans" => $id_jeans);
$res = $this->admin_model->DeleteData('jeans', $where);
}
This my model:
public function DeleteData($tabelname, $where)
{
if ($this->db->delete($tabelname, $where)) {
redirect("admin/admin/index");
}else {
echo "tidak berhasil";
}
$res = $this->db->delete($tabelname, $where);
return $res;
}
How can I delete an image with CodeIgniter?
You are only removing data from a table. If you want to delete a file from a directory:
public function DeleteData($tabelname, $where, $path_to_file)
{
if ($res = $this->db->delete($tabelname, $where)) {
unlink($path_to_file);
redirect("admin/admin/index");
}else {
echo "tidak berhasil";
}
}

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"

Dynamic checkbox and get the values from the checkbox checked

I am having difficulty creating dynamic checkboxes from db, and getting the values from the checkboxes when checked.
I have this Controller:
public function proporEvento(){
$natureza = $this->evento_model->naturezaEvento();
$apoio = $this->evento_model->apoioPertendido();
$espaco = $this->evento_model->espaco();
$material = $this->evento_model->material();
$suportgraf = $this->evento_model->suporteGrafico();
$audiovisual = $this->evento_model->audioVisual();
$data['title'] = 'Propor Evento';
$data['naturezaEvento'] = $natureza;
$data['apoioPertendido'] = $apoio;
$data['espaco'] = $espaco;
$data['material'] = $material;
$data['suporteGraf'] = $suportgraf;
$data['audioVisual'] = $audiovisual;
$this->load->view('cliente/clienteheaderdash_view', $data);
$this->load->view('cliente/clientemenu_view', $data);
$this->load->view('cliente/clienteproporevento_view', $data);
$this->load->view('cliente/clientefooterdash_view', $data);
}
Have this model:
public function naturezaEvento(){
$query = $this->db->get('tblnaturezaevento');
return $query->result();
}
public function apoioPertendido(){
$query = $this->db->get('tblapoio');
return $query->result();
}
public function espaco(){
$query = $this->db->get('tblespaco');
return $query->result();
}
public function material(){
$query = $this->db->get('tblmaterial');
return $query->result();
}
public function suporteGrafico(){
$query = $this->db->get('tblsuportegraf');
return $query->result();
}
public function audioVisual(){
$query = $this->db->get('tblaudiovisual');
return $query->result();
}
...and I have this view (one part for example):
<label>Apoio Pertendido</label>
<div class="form-group">
<?php foreach ($apoioPertendido as $row) { ?>
<label>
<input type="checkbox" class="flat-red" name="apoiopretendido[]" value="<?php echo $row->idApoio ?>" /> <?php echo $row->descricao; ?>
</label>
</br>
<?php } ?>
</div>
this code create the <input type="checkbox"...> correctly but how can I get the values from checked checkbox?
My form to go with this controller function:
public function etapa2(){
//$this->load->library('form_validation');
// $this->form_validation->set_rules('naturezaEvento', 'naturezaEvento', '|required|');
//$this->form_validation->set_rules('denominacao', 'denominacao', '|required|');
// $this->form_validation->set_rules('datainicio', 'datainicio', '|required|');
// $this->form_validation->set_rules('horainicio', 'horainicio', '|required|');
// $this->form_validation->set_rules('datafim', 'datafim', '|required|');
// $this->form_validation->set_rules('datainicio', 'datainicio', '|required|');
//if($this->form_validation->run() == FALSE){
//$this->index();
//}else{
$datageral['idcliente'] = $this->session->userdata('idcliente');
$datageral['idnatureza']=$this->input->post('naturezaEvento'); //insere o id do campo natureza da tabela tblnaturezaevento
$datageral['denominacaotitulo'] = $this->input->post('denominacao');
$datageral['datainicio']=$this->input->post('datainicio');
$datageral['horainicio']=$this->input->post('horainicio');
$datageral['datafim']=$this->input->post('datafim');
$datageral['horafim']=$this->input->post('horafim');
$datageral['planotrabalho']=$this->input->post('planotrabalho');
$datageral['raidertecnico']=$this->input->post('raidertecnico');
$datageral['programa']=$this->input->post('programa');
$datageral['mesa']=$this->input->post('mesa');
$datageral['notas']=$this->input->post('notas');
//'valorprovisorio' => $this->input->post('notas'), TODO fazer o valor provisório
//checkbox apoio
$apoiopertendido = $this->evento_model->apoioPertendido();
foreach ($apoiopertendido as $row) {
if ($this->input->post($row->checked, TRUE)===true){
$datageral[$row->tag] = $this->input->post($row->tag);
}
}
//checkbox espaços
$espacopertendido = $this->evento_model->espaco();
//$esp = array();
foreach ($espacopertendido as $row) {
if ($this->input->post($row->tag, TRUE)===true){
$datageral[$row->tag] = $this->input->post($row->tag);
}
}
//Material Necessário
$material = $this->evento_model->material();
//$materialnecessario = array();
foreach ($material as $row) {
$datageral[$row->tag] = $this->input->post($row->tag);
}
//checkbox suportes graficos
$suporteGrafico = $this->evento_model->suporteGrafico();
//$suporte = array();
foreach ($suporteGrafico as $row) {
if ($this->input->post($row->tag, TRUE)===true){
$datageral[$row->tag] = $this->input->post($row->tag);
}
}
//Registo Audio Visual
$audioVisual = $this->evento_model->audioVisual();
//$audiov = array();
foreach ($audioVisual as $row) {
if ($this->input->post($row->tag, TRUE)===true){
$datageral[$row->tag] = $this->input->post($row->tag);
}
}
$this->load->view('cliente/clienteheaderdash_view');
$this->load->view('cliente/clientemenu_view');
$this->load->view('cliente/clienteetapa2_view', $datageral);
$this->load->view('cliente/clientefooterdash_view');
// }
}

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);
}

Categories