Editing and updating an item in CodeIgniter - php

I'm having trouble to edit and update an item in my first CodeIgniter project. When I click on the edit button, first of all, it loads the view with the inputs filled with the informations of that item on the database, but it doesn't load the bootstrap that I'm using.
Then, when I click the "Edit" button, returns lots of errors saying that:
my function on the controllers is missing an argument and the variable is undefined, and
my view has an undefined offset and is trying to get property of non-object.
All the other commands for the CRUD are working, except this.
The version of CodeIgniter I'm using is 2.2.6
Codes:
Model:
function edit($id)
{
$this->db->where('id', $id);
$query = $this->db->get('products');
return $query->result();
}
function update($data)
{
$this->db->where('id', $data['id']);
$this->db->set($data);
return $this->db->update('products');
}
Controller:
function edit($id)
{
$data['title'] = "Edit Product";
$data['product_data'] = $this->model->edit($id);
$this->load->view('productEdit', $data);
}
function update()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<span>', '</span>');
$validations = array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required|max_length[255]'
),
array(
'field' => 'price',
'label' => 'Price',
'rules' => 'trim|required|max_length[255]'
),
array(
'field' => 'stock_quantity',
'label' => 'In Stock',
'rules' => 'trim|required|max_length[255]'
)
);
$this->form_validation->set_rules($validations);
if ($this->form_validation->run() === FALSE) {
$this->edit($this->input->post('id'));
} else {
$data['id'] = $this->input->post('id');
$data['name'] = $this->input->post('name');
$data['price'] = $this->input->post('price');
$data['stock_quantity'] = $this->input->post('stock_quantity');
if ($this->model->update($data)) {
redirect('products');
} else {
log_message('error', 'Error');
}
}
}
View:
<?php echo form_open('products/edit/', 'id="form-products"'); ?>
<input type="hidden" name="id" value="<?php echo $product_data[0]->id; ?>"/>
<label for="nome">Product Name:</label><br/>
<input type="text" name="name" value="<?php echo $product_data[0]->name; ?>"/>
<div class="error"><?php echo form_error('name'); ?></div>
<label for="email">Price:</label><br/>
<input type="text" name="price" value="<?php echo $product_data[0]->price; ?>"/>
<div class="error"><?php echo form_error('price'); ?></div>
<label for="email">In Stock:</label><br/>
<input type="text" name="stock_quantity" value="<?php echo $product_data[0]->stock_quantity; ?>"/>
<div class="error"><?php echo form_error('stock_quantity'); ?></div>
<input type="submit" name="update" value="Update" />
<?php echo form_close(); ?>
Thank you for your time.

Try this one
Update your model
function edit($id)
{
$this->db->where('id', $id);
$query = $this->db->get('products');
return $query->row(0);
}
and then in your view.
<input type="hidden" name="id" value="<?php echo $product_data->id; ?>"/>
also change your form action
products/update/

Related

Codeigniter - inserting into multiple tables

I am having problems with a booking form in Codeigniter; when a visitor makes a booking, the details are supposed to be inserted into two tables in a database ('reservation', and 'period', there is an FK from 'reservation' to 'period').
When I try to make the booking, nothing appears in the database, and I can't tell if it a problem with the form, or between the controller and model (there are no errors thrown - just nothing in the db). I tried to follow the logic from this example.
here is my form (gite-booking-form.php):
<html>
<head>
<title>Gite booking form</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('GiteCtl/giteBookingForm'); ?>
<h5>Select a gite:</h5>
<?php
$gitenames = array('giteA', 'giteB', 'giteC', 'giteD');
$gitename = isset($_POST['gitename']) && in_array($_POST['gitename'], $gitenames) ? $_POST['gitename'] : 'giteA';
echo '<select name="gitename">';
foreach ($gitenames as $option) {
echo '<option value="' . $option . '"' . (strcmp($option, $gitename) == 0 ? ' selected="selected"' : '') . '>' . $option . '</option>';
}
echo '</select>';
?>
<h5>Start date</h5>
<input type="date" value="<?php echo set_value('start_date'); ?>"/>
<h5>End date</h5>
<input type="date" value="<?php echo set_value('end_date'); ?>"/>
<div><input type="submit" value="Submit"/></div>
</form>
</body>
</html>
my model (Gite.php):
<?php
class Gite extends CI_Model
{
public function __construct() {
parent::__construct();
}
public function reservationInsert($table, $data)
{
$query = $this->db->insert($table, $data);
return $this->db->insert_id();
}
}
and the controller:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class GiteCtl extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->model('Gite');
$this->load->library('calendar');
$this->load->library('form_validation');
$this->load->library('session');
$this->load->model('Visitors');
}
public function isLoggedIn()
{
$isLoggedIn = $this->session->userdata('isLoggedIn');
if (!isset($isLoggedIn) || $isLoggedIn != TRUE) {
echo 'In order to book a gite, you must first login';
echo 'button: visitor-login.php'; // I will add this later
} else {
$this->giteBookingForm();
}
}
public function giteBookingForm()
{
$this->form_validation->set_rules('gite_selection', 'gite_select', 'required');
$this->form_validation->set_rules('start_date', 'startDate', 'required', array('required' => 'You must choose a %s.'));
$this->form_validation->set_rules('end_date', 'endDate', 'required', array('required' => 'You must provide an %s.')
);
if ($this->form_validation->run() == FALSE) {
$this->load->view('gite-booking-form');
} else {
$start_date = $this->input->post('start_date');
$end_date = $this->input->post('end_date');
$isHauteSaison = 1;
$isWeekend = 1;
$period_data = array(
'start_date' => $start_date,
'end_date' => $end_date,
'isHauteSaison' => $isHauteSaison,
'isWeekend' => $isWeekend
);
$gite_selection = $this->input->post('gite_selection');
$visitor_email = $this->session['visitorName'];
$price = 100.00;
$period_id = $this->Gite->reservationInsert('period', $period_data);
$reservation_data = array(
'gite_selection' => $gite_selection,
'visitor_email' => $visitor_email,
'price' => $price,
'period' => $period_id
);
$insert = $this->Gite->reservationInsert('reservation', $reservation_data);
}
}
}
Thanks,
E.
In the end it was the form; the php for retrieving data from the form was more complicated than I thought:
<h5>Select a gite:</h5>
<?php
$gitenames = array('giteA','giteB','giteC','giteD');
$gitename = isset($_POST['gitename']) && in_array($_POST['gitename'],$gitenames)?$_POST['gitename']:'giteA';
echo '<select name="gitename">';
foreach($gitenames as $option) {
echo '<option value="'.$option.'"'.(strcmp($option,$gitename)==0?' selected="selected"':'').'>'.$option.'</option>';
}
echo '</select>';
?>
<h5>Start date</h5>
<input type="date" class="form-control" name="start_date" value="<?php echo isset($start_date) ? set_value('start_date', date('Y-m-d', strtotime($start_date))) : set_value('start_date'); ?>">
<h5>End date</h5>
<input type="date" class="form-control" name="end_date" value="<?php echo isset($end_date) ? set_value('end_date', date('Y-m-d', strtotime($end_date))) : set_value('end_date'); ?>">

codeigniter: Update table from another table with session

I'm having some challenge updating table a form joined with session userdata from another table. Each time I run, it displays undefined function. Please let me know where I'm getting it wrong so could fix it.Please find time to review it
I'm a newbie.
Here's the controller
public function index()
{
if ( $this->session->userdata('logged_in') )
{
$id = $this->session->userdata('id');
$this->load->model('Userinfo_model');
$data['result'] = $this->Userinfo_model->get_users($id);
$this->load->view("usermain_info", $data);
}
}
public function update_user (){
$data = $this->input->post('userId');
$id = array(
'balance' => $this->input->post('balance'),
'id' => $this->input->post('id')
);
$this->Userinfo_model->update_user($id, $data);
$this->index();
}
Model
function get_users($userid)
{
if (isset($this->session->userdata['logged_in'])) {
$userid = ($this->session->userdata['logged_in']['id']);
} else {
header("location: nwpgroup/nwp2/index.php");
}
/* all the queries relating to the data we want to retrieve will go in here. */
$query = $this->db->query("SELECT * FROM walletbalance WHERE userId='$userid'");
return $query;
}
function update_user($id,$data){
if (isset($this->session->userdata['logged_in'])) {
$data = ($this->session->userdata['logged_in']['id']);
} else {
header("location: nwpgroup/nwp2/index.php");
}
$this->db->where('userId', $data);
$this->db->update('walletbalance', $id);
}
View
<form method="post" action="<?php echo base_url() . "index.php/userinfo/update_user"?>">
<?php if($result->num_rows() == 0){
echo 'No user found';
}
else {
foreach ( $result->result_array() as $new_user ){ ?>
<h4>Your name:<input value=" <?php echo $new_user['balance'] ?>" type="text" /> </h4><br />
<h4>Your name:<input value=" <?php echo $new_user['id'] ?>" type="text"/> </h4><br/>
<h4>Your name: <input value="<?php echo $new_user['userId'] ?>" type="hidden"/> </h4>
<input type="submit" id="submit" name="dsubmit" value="Update">
<?php }
}
?>
Error message
Message: Undefined property: Userinfo::$Userinfo_model
and
Message: Call to a member function update_user() on null
Thanks, I'm grateful
change your view as follows :
<form method="post" action="<?php echo base_url() . "index.php/userinfo/update_user"?>">
<?php if($result->num_rows() == 0){
echo 'No user found';
}
else {
foreach ( $result->result_array() as $new_user ){ ?>
<h4>Your name:<input value=" <?php echo $new_user['balance'] ?>" type="text" name="balance" /> </h4><br />
<h4>Your name:<input value=" <?php echo $new_user['id'] ?>" type="text" name="id" /> </h4><br/>
<h4>Your name: <input value="<?php echo $new_user['userId'] ?>" type="hidden" name="userId"/> </h4>
<input type="submit" id="submit" name="dsubmit" value="Update">
<?php }
}
?>
</form>
form will send data to server only if the element has a name
and you cannot submit a form multiple times. The above code will create update button for each row. So if you want to update all the records in a single updation, use update_batch() in codeigniter. and change view as follows :
foreach ( $result->result_array() as $new_user ){ ?>
<h4>Your name:<input value=" <?php echo $new_user['balance'] ?>" type="text" name="balance" /> </h4><br />
<h4>Your name:<input value=" <?php echo $new_user['id'] ?>" type="text" name="id" /> </h4><br/>
<h4>Your name: <input value="<?php echo $new_user['userId'] ?>" type="hidden" name="userId"/> </h4>
<?php } ?>
<input type="submit" id="submit" name="dsubmit" value="Update">
for reference : https://www.codeigniter.com/userguide3/database/query_builder.html#updating-data
In your update_user function you didn't include the usermain_info model. That is why the error is coming.
Please create constructor function and include the model in it. I have updated your code. Try with this.
<?php
function __construct() {
parent::__construct();
$this->load->library('session');
$this->load->model('Userinfo_model');
}
public function index(){
if ( $this->session->userdata('logged_in') ){
$id = $this->session->userdata('id');
$data['result'] = $this->Userinfo_model->get_users($id);
$this->load->view("usermain_info", $data);
}
}
public function update_user (){
$data = $this->input->post('userId');
$id = array(
'balance' => $this->input->post('balance'),
'id' => $this->input->post('id')
);
$this->Userinfo_model->update_user($id, $data);
$this->index();
}
?>

update multiple form using codeiginiter

I want to update data for multiple users using codeginiter, I used the bellow script but it only updates for one user.
<?php echo form_open(base_url() . 'get/save_payment', array('role' => 'form')); ?>
<?php foreach ($mature as $key => $value) { ?>
<input type="text" class="form-control" value="<?php echo $value->id; ?>" readonly name="id[]">
<input type="text" class="form-control" value="<?php echo $value->name; ?>" readonly name="name[]">
<input type="text" class="form-control" value="0" readonly name="amount[]">
<?php } ?>
<button type="submit" class="btn btn-success">Confirm Request</button>
<?php echo form_close(); ?>
CONTROLLER
public function save_payment() {
$this->load->library('form_validation');
$this->form_validation->set_rules('id[]', 'id', 'required|trim');
$this->form_validation->set_rules('name[]', 'name', 'trim');
$this->form_validation->set_rules('amount[]', 'Amount', 'required|max_length[4]|trim|strip_tags');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('id', set_value('id'));
$this->session->set_flashdata('name', set_value('name'));
$this->session->set_flashdata('amount', set_value('amount'));
$this->payment();
} else {
$id = set_value('id[]');
$data['amount'] = set_value('amount[]');
$data['name'] = set_value('id[]');
$this->dashboard->update_ph($data,$id);
}
}
Here is the MODEL :
public function update_ph($data,$id)
{
$this->db->where('id', $id);
$this->db->update('gw_ph', $data);
}
Kindly explain on how I can go through this code and get it working without error.
Thanks
Codeigniter use 'name' attributte for get data from 'input' and you use same 'name' attributte for all of your readonly input

Update the database with codeigniter and display the updation in same page

I am trying to update the data to the database by php CodeIgniter and display the result in the same page during update. Below is my code.The problem is it didn't show any error message and didn't update the values in the database and It is not displaying any values in the page after update. Please help.
View Page
<?php
echo form_open('Welcome/service1');
?>
<input type="hidden" name="servicer_id" value="<?php echo $value['service_id']?>">
<input type="hidden" name="servicer_name" value="<?php echo $value['servicer_name']?>">
<input type="hidden" name="servicer_email" value="<?php echo $value['servicer_email']?>">
<input type="hidden" name="servicer_checkin" value="<?php echo $value['servicer_checkin']?>">
<input type="hidden" name="servicer_checkout" value="<?php echo $value['servicer_checkout']?>">
<input type="hidden" name="servicer_requestdate" value="<?php echo $value['servicer_requestdate']?>">
<input type="hidden" name="servicer_detail" value="<?php echo $value['servicer_detail']?>">
<input type="hidden" name="servicer_contact" value="<?php echo $value['servicer_contact']?>">
<input type="hidden" name="servicer_priority" value="<?php echo $value['servicer_priority']?>">
<label class="radio-inline">
<input type="radio" <?php if($value['status']=="Complete") {?> checked="checked"<?php } ?> name="current_status" value="Complete">Complete
</label>
<label class="radio-inline">
<input type="radio" <?php if($value['status']=="Ongoing") {?> checked="checked"<?php } ?> name="current_status" value="Ongoing">Ongoing
</label>
<label class="radio-inline">
<input type="radio" <?php if($value['status']=="Rejected") {?> checked="checked"<?php } ?> name="current_status" value="Rejected">Rejected
</label>
<button type="submit" class="btn btn-default">
<span>Status</span>
</button>
<?php
echo form_close();
?>
Controller page
public function service1()
{
$this->load->helper('url');
$page_id =$this->uri->segment(3);
$this->load->model('Login_set');
$this->Login_set->add_status();
$data['s']=$this->Login_set->select2();
$this->load->view('App_stay/pages/hotel1_service.php',$data);
}
Model page
public function add_status()
{
this->load->database();
this->load->helper('url');
hotel_id=1;
servicer_name= $this->input->post('servicer_name');
servicer_email= $this->input->post('servicer_email');
servicer_checkin= $this->input->post('servicer_checkin');
servicer_checkout= $this->input->post('servicer_checkout');
servicer_requestdate= $this->input->post('servicer_requestdate');
servicer_detail= $this->input->post('servicer_detail');
servicer_contact= $this->input->post('servicer_contact');
servicer_priority= $this->input->post('servicer_priority');
status= $this->input->post('status');
service_id= $this->input->post('servicer_id');
data=array('hotel_id'=>$hotel_id,'servicer_name'=>$servicer_name,'servicer_email'=>$servicer_email,'servicer_checkin'=>$servicer_checkin,'servicer_checkout'=>$servicer_checkout,'servicer_requestdate'=>$servicer_requestdate,'servicer_detail'=>$servicer_detail,'servicer_contact'=>$servicer_contact,'servicer_priority'=>$servicer_priority,'status'=>$status);
this->db->where('service_id',$service_id);
this->db->update('service_hotel1',$data);
}
You are passing inputs to the model but they are getting passed to the controller function.. please update
Controller:
public function service1()
{
/** you are posting the form to this function and not to the model.
* which is why all input->post must be here
*/
$servicer_name = $this->input->post('servicer_name');
$servicer_email = $this->input->post('servicer_email');
$servicer_checkin = $this->input->post('servicer_checkin');
$servicer_checkout = $this->input->post('servicer_checkout');
$servicer_requestdate= $this->input->post('servicer_requestdate');
$servicer_detail = $this->input->post('servicer_detail');
$servicer_contact = $this->input->post('servicer_contact');
$servicer_priority = $this->input->post('servicer_priority');
$status = $this->input->post('status');
$service_id = $this->input->post('servicer_id');
$this->load->helper('url');
$page_id = $this->uri->segment(3);
$this->load->model('Login_set');
$this->Login_set->add_status($servicer_name, $servicer_email, $servicer_checkin, $servicer_checkout, $servicer_requestdate, $servicer_detail, $servicer_contact, $servicer_priority, $status, $service_id);
$data['s'] = $this->Login_set->select2();
$this->load->view('App_stay/pages/hotel1_service',$data); //also view must be loaded without .php so $this->load->view('App_stay/pages/hotel1_service',$data);
}
Model:
public function add_status($servicer_name, $servicer_email, $servicer_checkin, $servicer_checkout, $servicer_requestdate, $servicer_detail, $servicer_contact, $servicer_priority, $status, $service_id)
{
$this->load->database();
$this->load->helper('url');
$hotel_id =1 ;
$data = array(
'hotel_id' => $hotel_id,
'servicer_name' => $servicer_name,
'servicer_email' => $servicer_email,
'servicer_checkin' => $servicer_checkin,
'servicer_checkout' => $servicer_checkout,
'servicer_requestdate' => $servicer_requestdate,
'servicer_detail' => $servicer_detail,
'servicer_contact' => $servicer_contact,
'servicer_priority' => $servicer_priority,
'status' => $status
);
$this->db->where('service_id',$service_id);
$this->db->update('service_hotel1',$data);
}

set value default codeigniter

I have this function (get_profile_info)
function get_profile_info()
{
$this->db->where('username',$this->session->userdata('username'));
$get_profile_info = $this->db->get('memberships');
if($get_profile_info->num_rows() == 1){
foreach ($get_profile_info->result() as $row)
{
echo $row->firstname;
echo $row->lastname;
}
}
}
The question is how do i put this results: firstname and lastname into input form default set_value: echo "Firstname".form_input('firstname2');
Try this code:
foreach($get_profile_info->result() as $row)
{
$data = array(
'name' => 'firstname',
'id' => 'firstname',
'value' => $row->firstname,
);
echo form_input($data);
// do the same for lastname
}
Set input value of your view file like this.
<input type="text" value="<?php echo $data['firstname']; ?>" />
you have to pass data array from controller.
Try this
function get_profile_info()
{
$this->db->where('username',$this->session->userdata('username'));
$get_profile_info = $this->db->get('memberships');
if($get_profile_info->num_rows() == 1){
return $get_profile_info->row();
}
function your_controller
{
$data['row'] = get_profile_infor()
$this->load->view("yourview",$data)
}
IN View
<input type="text" name="firstname" value="<?php echo set_value('firstname',$row->firstname)?>" />
<input type="text" name="lastname" value="<?php echo set_value('lastname',$row->lastname)?>" />

Categories