codeigniter update method not working - php

I am new to codeigniter and trying to write an update function to update information in my database. I've gone through a few tutorials but for some reason my code is not working! Any tips or assistance would be greatly appreciated. I'm just testing with two fields right now, name and email, and I get a blank page when I go to my update view.
Here is my model method:
function get_by_id($id){
return $this->db->get_where('table',array('id'=>$id));
}
function update($id){
$attributes=array(
'name'=> $this->input->post('Name'),
'email'=> $this->input->post('Email')
);
return $this->db->where('id',$id)
->update('table',$attributes);
}
And here is my relevant controller code:
function edit(){
$data['row']=$this->Mymodel->get_by_id($id)->result();
$data['name']= 'Name';
$data['email']='Email';
$this->load->view('updateview', $data);
}
function update($id){
$this->load->model('Mymodel');
$this->Mymodel->update($id);
if($this->input->post()){
redirect('kittens/view/'.$id, 'refresh');
}
And here is my update view:
<?php echo form_open('kittens/update/')
echo form_hidden('id', $row[0]->id);
foreach($attributes as $field_name){
echo '<p>' . $field_name;
echo form_input($field_name, $row[0]->$field_name) . '</p>';
}
echo form_submit('', 'Update');
echo form_close();
?>
Any help would be appreciated! Not sure what specific part is giving me the trouble!

Use the following template:
Controller:
public function updateData(){
....
$data = array(
"columnName" => $columnValue
);
$whereValue = $someNumber;
$this->model_name->updateTable($data, $wherevalue);
...
}
Model:
public function updateTable($data, $whereValue){
$this->db->where('columnName', $whereValue);
$this->db->update('tableName', $data);
}

the first thing is that the model "MyModel" isn't loaded on the "edit" method in the controller.
If you're planning to use that specific model in every function of your controller you should load it in the constructor (so you don't have to load it every time).
Using$this->input->post('Name') in a model is a bad idea. You should receive that data in the controller process it (if you have to) and then send it to the method in the model.
I don't know if you can "chain" the db methods like this in codeigniter:
$this->db->where('id',$id)->update('table',$attributes);
try this:
$this->db->where('id',$id);
$this->db->update('table',$attributes);
Hope that helps

////////////model for update/////////////
public function update_customer_contacts($where, $data){
return $this->db->update('customer_contacts', $data, $where);
}
///////////////////update customer///////////////////
public function update_customer()
{
$data = array(
'company_name'=>$this->input->post('company_name'),
'address' =>$this->input->post('address'),
'telephone' =>$this->input->post('telephone'),
'fax' =>$this->input->post('fax'),
'email' =>$this->input->post('email'),
'website' =>$this->input->post('website'),
);
$res= $this->customer_model->update_customer(array('customer_id' => $this->input->post('customer_id')), $data);
;
echo json_encode($this->input->post());
}

Related

Retrieve data from database in codeigniter

I am new to Codeigniter so I'm having some difficulties I want to retrieve data from the database and load it in the view but I couldn't figure out how.
Here is my model:
public function viewClientWaterwell(){
$userid = get_client()->userid;
$waterwells = $this->db->select('*')
->from($this->table)
->where('ww_client_id', $userid)
->get()->result_array();
return $waterwells;
}
Here is my clientController:
public function viewClient()
{
$data['waterwells'] = $this->waterwell_model->viewClientWaterwell();
$this->data($data);
$this->view('waterwells/clients/viewClient');
$this->layout();
}
I want to pass some data in a view to the client side but I can't figure out how. I think there is some problem with my model but I cannot figure out what. I'm new to this and will appreciate your feedback. Thanks!
You just need to use second argument to pass data to your template or view file
Here is example to start
Inside your controller function
public function viewClient()
{
$data = array( 'myvar' => 'I love stackoverflow' );
$this->load->view('waterwells/clients/viewClient', $data);
}
And inside your template or view file you can access them by their name.
<?php echo $myvar; ?>

too few arguments for function error (updating data) CodeIgniter

there's an error appearing in my code for update. too few argument for function.
I searched the net and I'm not sure if I'm passing the id.
Controller:
public function update()
{
if($this->Admin_model->update($this->input->post(null, true))){
$this->session->set_flashdata('flash_msg', ['message' => 'User updated successfully', 'color' => 'green']);
} else {
$this->session->set_flashdata('flash_msg', ['message' => 'Error updating user.', 'color' => 'red']);
}
$this->admin_redirect('cms');
}
Model:
public function update($id, $data)
{
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
return $this->db->update($this->table, $data);
}
As #WILLIAM, stated in a comment, your update(...) method expects 2 parameters yet one is passed.
Change your update(...) method to this:
public function update($data)
{
$data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
$this->db->where('id', $data['id']);
return $this->db->update($this->table, $data);
}
This assumes that 'id' is part of your HTML form.i.e:
<input type="hidden" name="id" value="<?php echo $id ?>">
You need to call your model update function with 2 params in the controller code, but it seems you are calling it only with one parameter $data value is missing.
In below code:
if($this->Admin_model->update(**$this->input->post(null, true)**))
It should be called with 2 values first one should be an ID that identifies the record that you want to update in your model, and another should be the data that would be updated within that record.
Hope! you got the answer.

How to pass data controller to view in codeigniter

I am getting user profile fields from the database and want to display in my view but don't know to do this with the master layout.
this is my model
function fetchProfile($id,$page){
$query = $this->db->query("SELECT * FROM staff_master WHERE Id='$id'");
return $query->result();
}
this is my controller:
public function edit($id,$page){
$data['query'] = $this->StaffModel->fetchProfile($id,$page);
$data= array('content'=>'view_staff_edit');
$this->load->view('template_master',$data);
}
I am also trying to find a solution. I am passing user Id and another by URL (get method).
You are overwriting $data['query'] when you assign the array next:
$data['query'] = $this->StaffModel->fetchProfile($id,$page);
$data= array('content'=>'view_staff_edit');
Either do:
$data= array('content'=>'view_staff_edit');
$data['query'] = $this->StaffModel->fetchProfile($id,$page); // note position
Or:
$data = array(
'content' = 'view_staff_edit',
'query' => $this->StaffModel->fetchProfile($id,$page),
);
Access in view via $query and $content.
Unrelated:
You are also missing $page in your query, and its generally a good idea to declare gets as null if not set or you will get a notice: public function edit($id=null,$page=null){
Your overriding your first declaration of variable $data what you can do is to initialize them both at the same time.
Controller
public function edit($id,$page){
$data = array(
'query' => $this->StaffModel->fetchProfile($id,$page),
'content' => 'view_staff_edit'
);
$this->load->view('template_master',$data);
}
Then access it on your View file
<h1><?php echo $content ?></h1>
<?php foreach($query as $result): ?>
<p><?php echo $result->id ?></p>
<?php endforeach; ?>
Try doing something like this:
public function edit($id,$page) {
$data['query'] = $this->StaffModel->fetchProfile($id,$page);
$data['content']= 'view_staff_edit';
$this->load->view('template_master',$data);
}
YOUR MODEL
function fetchProfile($id){
return $this->db->get_where('Id' => $id)->result_array();
}
YOUR CONTROLLER
public function edit($id,$page){
$data = array(
'query' => $this->StaffModel->fetchProfile($id),
'content' => 'view_staff_edit',
);
$this->load->view('template_master',$data);
}
YOUR "template_master" VIEW
<?php foreach ($query as $res){?>
<span><?php echo $res['Id'];?></span> //User html content according to your requirements ALSO you can add all columns retrieved from database
<?php } ?>

Insert one row using different models/pages - CodeIgniter

I'm new to CodeIgniter and I'm building a simple I/O website. I have only one database, say test and only one table results, that looks like this:
screenshot of the table "results"
I have two views personal.php and songs.php. In the first one I collect the data values to be inserted into the fields 2,3, and 4, and the rest of the values are collected in the second view. They are then inserted into the table via their relevant models, personal_model and songs_model.
Now obviously, they will be inserted into 2 different rows which is not what I want. What is the trick here? How should I manage it? So far I have thought of getting the last ID but I have no idea how to do it. Thanks in advance!
personal.php (first view)
<?php echo validation_errors(); ?>
<?php echo form_open('data/personal'); ?> //passes the data to the controller that loads the personal_model.php
"some input fields"
<button type="submit" name="submit">Submit Data</button>
songs.php (second view)
<?php echo validation_errors(); ?>
<?php echo form_open('data/songs'); ?> //passes the data to the controller that loads the songs_model.php
"some input fields"
<button type="submit" name="submit">Submit Rating</button>
personal_model.php (first model)
<?php
class Personal_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function insert_personal()
{
$this->load->helper('url');
$data = array(
'age' => $this->input->post('user_age'),
'education' => $this->input->post('user_edu'),
'twitter' => $this->input->post('user_twitter'),
'facebook' => $this->input->post('user_facebook')
);
return $this->db->insert('results', $data);
}
}
songs_model.php (second model)
<?php
class Ratings_model extends CI_Model {
public function __construct()
{
$this->load->database();
}
public function insert_ratings()
{
$this->load->helper('url');
#$this->load->database();
$data = array(
'score' => $this->input->post('rating'),
'song1' => $this->input->post('rnd1'),
'song2' => $this->input->post('rnd2')
);
return $this->db->insert('results', $data);
}
}
Your Controller Function should be like this.
public function personal()
{
$lastInsertedID = $this->Personal_model->insert_personal();
$this->session->set_userdata("personalID",$lastInsertedID);
}
Set the last inserted id into session in your above controller function which should be return from your Personal_model. Here is code.
public function insert_personal()
{
$this->load->helper('url');
$data = array(
'age' => $this->input->post('user_age'),
'education' => $this->input->post('user_edu'),
'twitter' => $this->input->post('user_twitter'),
'facebook' => $this->input->post('user_facebook')
);
$this->db->insert('results', $data);
return $this->db->insert_id();
}
Then update your existing row in your insert_ratings function instead of insert record. Here is code.
public function insert_ratings()
{
$data = array(
'score' => $this->input->post('rating'),
'song1' => $this->input->post('rnd1'),
'song2' => $this->input->post('rnd2')
);
$personalID = $this->session->userdata("personalID");
$this->db->where("id",$personalID);
$this->db->update('results', $data);
return $this->db->affected_rows();
}
Then no new record will insert into table while submit your song.php form it will update the existing one.

Cannot insert values into database using codeigniter

trying to insert form values into database using codeigniter but nothing heppens.
my form is comment_form.php is like,
<?php echo validation_errors(); ?>
<?php echo form_open('news/comment_form'); ?>
Name<input type="text" name="comment_name"></input><br />
Email<input type="text" name="comment_email"></input><br />
Comment<input type="text" name="comment_body"></input><br />
<input type="submit" name="submit" value="Comment it" ></input>
</form>
here's my controller comments.php
class Comments extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('comment_model');
}
public function create_comment()
{
$this->load->helper('form');
$this->load->library('form_validation');
//$data['title'] = 'Create a news item';
$this->form_validation->set_rules('comment_name', 'comment_name', 'required');
$this->form_validation->set_rules('comment_email', 'comment_email', 'required');
$this->form_validation->set_rules('comment_body', 'comment_body', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/header', $data);
$this->load->view('news/comment_form');
$this->load->view('templates/footer');
} else {
$this->news_model->set_comment();
$this->load->view('news/success');
}
}
}
and this is my model comment_model.php
class Comment_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function set_comment()
{
//$this->load->helper('url');
//$slug = url_title($this->input->post('title'), 'dash', TRUE);
$datac = array(
'comment_name' => $this->input->post('comment_name'),
'comment_email' => $this->input->post('comment_email'),
'comment_body' => $this->input->post('comment_body')
);
return $this->db->insert('comments', $datac);
}
}
the problem is whenever i submitting the form it returns nothing, like nothing happened.please help.
In your comment_form.php change
echo form_open('news/create_comment');
to
echo form_open('comments/create_comment');
Why? Because the first parameter you give to form_open() is the action parameter. It will open a form tag like <form action="bla">. And news/create_comment is not the correct page you want to call. Your controller is named comments, that's why you put comments/create_comment.
In your comments.php change
$this->news_model->set_comment();
to
$this->comment_model->set_comment();
Why? Just simply pointing to the false model. Maybe a copypaste-error?
In your comment_model.php remove
$this->load->database();
And load it in your config.php (in the libraries array, add 'database').
Why? IMHO this is the more proper solution. You're probably gonna use your database pretty often, so why load that everytime?
If you still encounter problems, then we need more information. What exactly is not working. Do some debugging for us. After you call $this->news_model->set_comment() write var_dump($this->db->last_query());
this->news_model->set_comment()
Should be
this->comment_model->set_comment()
PS: sorry for the formatting. Mobile version doesn't read new lines.
Change :
$this->load->database();
echo form_open('news/comment_form');
$this->news_model->set_comment();
To:
$this->load->library('database');
echo form_open('news/create_comment');
$this->comment_model->set_comment();
It would be better if you load your database library in your autoload.php. Or in your controller's constructor.
In the set_comment function after $this->db->insert('comments', $datac); just echo the query using below command and try running the same query manually in the database, you may come to know the issue.
echo $this->db->last_query();
Get the posted values in controller instead of model and then pass them to model.
Controller function
public function create_comment()
{
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('comment_name', 'comment_name', 'required');
$this->form_validation->set_rules('comment_email', 'comment_email', 'required');
$this->form_validation->set_rules('comment_body', 'comment_body', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/header', $data);
$this->load->view('news/comment_form');
$this->load->view('templates/footer');
} else {
$data['comment_name'] = $this->input->post('comment_name'),
$data['comment_email'] = $this->input->post('comment_email'),
$data['comment_body'] = $this->input->post('comment_body')
$this->news_model->set_comment();
$this->load->view('news/success');
}
}
Model function
public function set_comment($data)
{
//$this->load->helper('url');
//$slug = url_title($this->input->post('title'), 'dash', TRUE);
$this->db->insert('comments', $data);
return $this->db->insert_id();
}
EDITS
The above code will work if you follow these steps.
Go to database.php in application/config and provide database connection settings like hostname , username , password and database name.
Then go to autoload.php in application/config and autoload the database library like this
$autoload['libraries'] = array('database');
Also remove the closing tags for input in your html form.
Try testing like this in controller before moving forward
$post = $this->input->post();
echo '<pre>';
print_r($post);
This will ensure you are receiving post data

Categories