Update function code igniter does not save changes - php

hi am making this edit function in my code igniter hmvc project. i am getting the value of the things i want to edit, and it is posted to the textbox i want to. but, i cannot save the changes. my model is this,
public function update(){
$sql = "UPDATE $this->table SET PROVINCE = ? WHERE PROV_ID = ?";
$input = array(
'PROVINCE' => $this->input->post('PROVINCE'),
'PROV_ID' =>$this->uri->segment(3)
);
// print_r($input);
// exit;
$query = $this->db->query($sql, $input);
return $query;
}
when i print_r the input, it says
Array ( [PROVINCE] => Province [PROV_ID] => )
i think dont get the uri value. how can i fix this?
here is my controller
/// EDIT
public function update(){
$data['content'] = $this->Provinces_Model->getrow();
$data['content_view'] = 'Provinces/edit_view';
$this->templates->admin_template($data);
}
public function update_row(){
if($this->Provinces_Model->update()){
redirect('Provinces/index');
}else{
$this->update();
}
}
}
here is my full model
//// EDIT
public function getrow(){
$this->db->where('PROV_ID', $this->uri->segment(3));
$query = $this->db->get($this->table);
return $query->row();
}
public function update(){
$sql = "UPDATE $this->table SET PROVINCE = ? WHERE PROV_ID = ?";
$input = array(
'PROVINCE' => $this->input->post('PROVINCE'),
'PROV_ID' =>$this->uri->segment(3)
);
// print_r($input);
// exit;
$query = $this->db->query($sql, $input);
return $query;
}
here is my edit view
<?php
echo form_open('Provinces/update_row');
?>
<p>
<label class="field" for="PROVINCE"><span>*</span>Province Name:</label>
<input type = "text" name="PROVINCE" class ="textbox-300" value= "<?php echo $content->PROVINCE; ?>">
<label class = "error"><?php echo form_error("PROVINCE"); ?></label>
</p>
<?php
echo form_submit('submit','Update');
echo form_close();
?>
here is the part of my table where i click to edit
<td><?php echo anchor("Provinces/update/$i->PROV_ID","<i class='fa fa-edit'>" ); ?></td>

Try this
public function update() {
$input = array(
'PROVINCE' => $this->input->post('PROVINCE'),
'PROV_ID' =>$this->uri->segment(3)
);
$this->db->where('prov_id',$input['PROV_ID']);
$this->db->update('province',$input);
}

get the all segments of URI in an array
For that use this line...
$segs = $this->uri->segment_array();
foreach ($segs as $segment)
{
echo $segment;
echo '<br />';
}
and use that specific key to get the ID or something else!!

Related

how to update multiple value in codeigniter

I have input data that I will fill with different values, I do multiple updates
but I have an error which is:
Unknown column 'Array' in 'field list' UPDATE service SET
charges_order = WHERE array id_service = '1'
how to overcome this?
example img
View
<?php $no = 1; foreach ($invoice as $m) { ?>
<tbody id="tbody">
<form class="form-signin" method="post" action="<?php echo base_url();?>backend/report/update/<?php echo $m->id_service; ?>">
<tr class="deleted">
<td><input type="text" class="form-control" name="charges_order[]" value="<?php echo $m->charges_order;?>"></td>
</tr>
</form>
</tbody>
<div class="box-footer">
<button type="submit" class="btn bg-blue btns-flat margin">Simpan</button>
</div>
<?php } ?>
Controller
public function update($id_service)
{
foreach ($this->input->post('charges_order') as $data) {
$data = array(
'charges_order' => $this->input->post('charges_order')
);
// echo '<pre>', print_r($data);
$this->M_report->update($id_service, $data);
redirect('backend/report');
}
}
Model
public function update($id_service, $data)
{
$this->db->where('id_service', $id_service);
$this->db->update('service', $data);
}
Change your controller to this-
public function update($id_service){
$charges_order = json_encode($this->input->post('charges_order'));
$data = array(
'charges_order' => $charges_order
);
$this->M_report->update($id_service, $data);
redirect('backend/report');
}
This should work for you.
You are in a loop. You must use the variable.
$data = array(
'charges_order' => $data
);
You can convert array into a string and then update the table.
//example
[1,2,3,4] -> "1,2,3,4"
Here is the code
public function update($id_service)
{
$data = array(
'charges_order' => implode(",", $_POST['charges_order'])
);
// echo '<pre>', print_r($data);
$this->M_report->update($id_service, $data);
redirect('backend/report');
}
When you are retrieving, you can reverse the process
public function get_orders($id_service)
{
$this->db->select('charges_order');
$this->db->where('id_service', $id_service);
$result = $this->db->get('service')->result_array();
return explode(",", $result["charges_order"]); //returns an array
}

Correct way to display my query

I have a query in my model that I need to print the data in my view
Model
function get_bank()
{
$query = $this->db->query("SELECT
(
12* (YEAR('account_add_date') - YEAR('start_date')) +
(MONTH('account_add_date') - MONTH('start_date'))
) AS differenceInMonth
->FROM ('bank')
WHERE mem_id = '".$this->session->userdata('id')."'");
return $query->result();
$data['account_age'] = $query->row_array();
}
and I am trying to print the output in my model, but its not working and I do not know where I have gone wrong. I am new to MVC and still getting used to it.
View
<h2>age of account</h2>
<?php
$age = $this->model('profiles_model' , $data );
print "<h2>$age</h2>";
?>
Controller
function index()
{
$data = array();
$this->load->model('user_profile/profiles_model');
$query = $this->profiles_model->get_bank();
if(!empty($query))
{
$data['records'] = $query;
}
$this->load->view('profile_view', $data);
}
Let's first write your code in proper convention.
Model
function get_bank() {
$mem_id = $this->session->userdata('id');
$query = $this->db
->select("12*(YEAR('account_add_date') - YEAR('start_date')) + (MONTH('account_add_date') - MONTH('start_date')) AS differenceInMonth")
->where('mem_id', $mem_id)
->get('bank');
return $query;
// $data['account_age'] = $query->row_array(); <-- Statement after return is useless.
}
Controller
function index() {
$data = array(
'records' => array()
);
$this->load->model('user_profile/profiles_model');
$bank = $this->profiles_model->get_bank();
if($bank->num_rows()){
$data['records'] = $bank->row_array();
}
$this->load->view('profile_view', $data);
}
View
Not sure what you are trying to do with the bank data but here's how you print the record
<p>Bank data</p>
<p><?=isset($records['differenceInMonth'])?$records['differenceInMonth']:"No record found"?></p>
You are not far away, do it this way:
Controller:
function index()
{
$this->load->model('user_profile/profiles_model');
$data = $this->profiles_model->get_bank();
$this->load->view('profile_view', $data);
}
Model:
function get_bank()
{
$query = $this->db->query("SELECT
(
12* (YEAR('account_add_date') - YEAR('start_date')) +
(MONTH('account_add_date') - MONTH('start_date'))
) AS differenceInMonth
->FROM ('bank')
WHERE mem_id = '".$this->session->userdata('id')."'");
return $query->result();
}
View:
<?php
foreach(differenceInMonth AS $age){
echo "<p>" . $age . "</p>";
}
When you load the view you are passing in $data with $data['records'] that has the data you are wanting to display.
Since that is how you pass the data into the view when you load it you will need to call it that way:
<?php
var_dump($records);
?>
You will also need to loop through the data as well assuming $records is an array of the query results or use var_dump instead of print just to verify the data is there.
Reading through these will help going forward:
https://codeigniter.com/user_guide/general/views.html
https://codeigniter.com/user_guide/general/models.html

codeigniter array and loop to insert for multiple data

I want to make an invoice form. For this reason i need to insert multiple data at once. for example I want to input db 5 category sale or purchase product at a time. But I am not interested with insert_batch. I try but i got some null value in db.
My Model is:
<?php
class Purchase_model extends CI_Model{
public function purchase(){
$price = $this->input->post('price');
$quantity = $this->input->post('quantity');
$date = $this->input->post('date');
$vendor_name = $this->input->post('vendor_name');
$model = $this->input->post('model');
$invoice_no = $this->input->post('invoice');
//$temp = count($this->input->post('vendor_name'));
for($i=0; $i<10; $i++){
$data = array(
'date'=>$date[$i],
'vendor_name'=>$vendor_name[$i],
'model'=>$model[$i],
'price' =>$price[$i],
'purchase_quantity'=>$quantity[$i],
'amount' =>$price[$i]*$quantity[$i],
'invoice_no'=>$invoice_no[$i]
);
$insert = $this->db->insert('purchase',$data);
return $insert; }
}}
My controller is:
public function purchase(){
if($this->Purchase_model->purchase()){
$this->session->set_flashdata('Success',
'You are entered data successfully');
redirect('home/purchase_form');
}
}
My view for example:
<?php echo form_label ('Price:'); ?>
<select name="price[]" id="price" class="input-xlarge">
</select>
<?php echo form_label ('Quantity'); ?>
<?php
$data = array ('name' =>'quantity[]',
'class' =>'input-xlarge',
'value' => set_value('quantity')); ?>
<?php echo form_input ($data); ?>
<?php echo form_label ('Price:'); ?>
<select name="price[]" id="price2" class="input-xlarge">
</select>
<?php echo form_label ('Quantity'); ?>
<?php
$data = array ('name' =>'quantity[]',
'class' =>'input-xlarge',
'value' => set_value('quantity')); ?>
<?php echo form_input ($data); ?>
Please help.
The problem has been solved. My mistake in my model. The correct model is
public function purchase(){
$data = array();
$temp = count($this->input->post('quantity'));
for($i=0; $i<$temp; $i++){
$invoice_no = $this->input->post('invoice');
$date = $this->input->post('date');
$price = $this->input->post('price');
$quantity = $this->input->post('quantity');
$vendor_name = $this->input->post('vendor_name');
$model = $this->input->post('model');
if( $quantity[$i]!= '') {
$data[] = array(
'date'=>$date,
'vendor_name'=>$vendor_name[$i],
'model'=>$model[$i],
'price' =>$price[$i],
'purchase_quantity'=>$quantity[$i],
'amount' =>$price[$i]*$quantity[$i],
'invoice_no'=>$invoice_no
);} }
$insert = count($data);
if($insert)
{
$this->db->insert_batch('purchase', $data);
}
return $insert;
}
Thanks every one who try to help me.

Inserting two fields into a database

I am struggling to add data and a category_id in to my database using the MVC architecture.
here is my controller method, which is probably all wrong.
public function create(){
$data['categories'] = $this->get_m->createJoke();
$data = array(
'joke' => $this->input->post('joke'),
'category_id' => $this->input->post('category')
);
$this->get_m->createJoke($data);
$this->load->view('create', $data);
}
Here is my model method:
function createJoke($data){
// Retrieving categories from the database
$categories = $this->db->query('SELECT * FROM category');
$this->db->insert('jokes', $data);
return $categories->result();
}
and finally, this is the form which i want to be able to select a category for a joke:
<?php
echo form_open('home/create');
?>
<p>
<label for="joke">Joke</label>
<input type="text" name="joke" id="joke" />
</p>
<select class="category" name="category">
<option value=0>Select something…</option>
<?php foreach ($categories as $category) { ?>
<option value="<?php echo $category['category_id']; ?>"<?php echo $category_id == $category['category_id'] ? ' selected="selected"' : ''; ?>><?php echo $category['name']; ?></option>
<?php } ?>
</select>
<p>
<input type="button" value="Submit"/>
</p>
<?php echo form_close(); ?>
Before i just had the joke label up (although it did add data in the database), it only added a "0" for some reason.
I have been watching some CRUD tutorials which focus on inserting data, and this is the best i can come up with really!
You didn't check whether form is submitted or not in your controller.
public function create(){
$data['categories'] = $this->get_m->createJoke();
if($this->input->post("joke")!="" and $this->input->post("category")!="") // check post have some value
{
$data = array(
'joke' => $this->input->post('joke'),
'category_id' => $this->input->post('category')
);
$this->get_m->createJoke($data);
}
$this->load->view('create', $data);
}
try this i think this will work
//controller
public function create(){
$data = array(
'joke' => $this->input->post('joke'),
'category_id' => $this->input->post('category')
);
$this->get_m->createJoke($data);
$this->load->view('create', $data);
}
public function selectdata(){
$data['categories'] = $this->get_m->get_joke_categoryid();
}
//model
function createJoke($data){
$this->db->insert('joker', $data);
$this->session->set_flashdata("message", "Contract record successfully created.");
function get_joke_categoryid(){
$query = $this->db->get('joker');
return $query->result();
}
kindly check this if this code help you

Twitter Typeahead in CodeIgniter. Not passing array datum to hidden form field

I'm trying to use the typeahead.js Twitter Typeahead (not Bootstrap typeahead) to display names pulled from a mysql table using the CodeIgniter framework. The model also collects id values along with the name.
The controller and model seem to be presenting the correct array format.
Model
class People_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_person($name) {
$mode = $this->uri->segment(3);
$this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
$this->db->from('people');
if($mode == 'signin')
$this->db->where("status !=", "enter");
else
$this->db->where("status", "enter");
$this->db->like("concat(firstName,' ', lastName)", $name);
$this->db->order_by('name');
$query = $this->db->get();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$new_row['value']=htmlentities(stripslashes($row['name']));
$new_row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $new_row; //build an array
}
}
echo json_encode($row_set); //format the array into json data
}
}
Controller (relevant functions)
function get_person() {
$this->config->set_item('disable_template', TRUE);
$this->load->model('People_model');
$name = $this->input->get_post();
$this->People_model->get_person($name);
}
function dosigninout() {
$mode = $this->uri->segment(3);
switch($mode) {
case 'signin':
$mode = 'enter';
break;
case 'signout':
$mode = 'exit';
break;
default:
$this->load->view("home/error", array('error' => "Invalid mode specified."));
}
$meeting = $this->_currentMeeting();
$person = $this->input->post('person_id');
if(!$this->_validPerson($person, $this->input->post('name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('name')." who has an ID of $person. The name and ID don't match."));
$this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
$this->db->where("id", $person);
$this->db->update("people", array('status' => $mode));
$redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
if($redirectTo) redirect($redirectTo);
else redirect('attendance');
}
Sample JSON data returned
[{"value":"Anna Woodhouse","id":"2"},{"value":"Elaine Woodhouse","id":"4"}]
View
$baseURL = base_url();
$extraHeadData = "";
?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm"))?>
<fieldset>
<legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
<div class="control-group">
<div class="controls">
<input type="hidden" name="person_id" id="person_id" value="" />
<input class="people-typeahead" type="text" id="typeahead" name="name" placeholder="person's full name"/>
</div>
</div>
</fieldset>
<div class="form-actions">
<?=form_submit('','Save changes','class="btn btn-primary"'); ?>
</div>
</form>
<script src="http://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.4.4/underscore-min.js"></script>
<script src="<?php echo $baseURL?>assets/js/typeahead.min.js"></script>
<script>
$(function($) {
$('input.people-typeahead').typeahead({
name: 'people',
remote: 'http://localhost/badgeentry/index.php/attendance/get_person',
dataType: 'json'
});
$("#people-typeahead").on("typeahead:selected typeahead:autocompleted", function(e,datum) {
$(person_id).val() = datum.id
});
});
</script>
In the form field I get the correct drop down list, but when an item is selected any new database entry has an id of "0" instead of the selected name id. I'm almost certain that this is an issue with the javascript code in the view not being correct, but quite frankly, I have no js skills to sort it out!
I see an issue here :
$(person_id).val() = datum.id
You are using jQuery's .val() incorrectly and the use of the selector is wrong too. It should look like :
$("#person_id").val(datum.id);
jQuery .val() documentation
I finally figured out how to get this working. Part of the problem was that I could find no examples of using typeahead.js in CodeIgniter that showed how the various script, view, controller and model components interact. I tried switching to Twitter bootstrap typeahead. However, despite finding references to using it with an arrays rather than a string, I still could not get a working solution.
In the end I went back to Twitter typeahead and started from scratch. I found this tutorial helped enormously:
Twitter Bootstrap typeahead.js with underscore.js Templating – A Tutorial - Alan Greenblatt
I'm posting what worked for me in case it can help anyone else with similar issues. This version also includes setting the remote source as a variable which allowed me to define it through PHP so that I could select data in the model based on the URL.
Model
class People_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_person($name) {
$modeinout = $this->uri->segment(3);
$this->db->select("id, CONCAT(firstName,' ', lastName) AS name, type",FALSE);
$this->db->from('people');
if($modeinout == 'signin'){
$this->db->where('status !=', 'enter');
}
else {
$this->db->where('status', 'enter');
}
$this->db->like("concat(firstName,' ', lastName)", $name);
$this->db->order_by('name');
$query = $this->db->get();
if($query->num_rows > 0){
foreach ($query->result_array() as $row){
$new_row['name']=htmlentities(stripslashes($row['name']));
$new_row['id']=htmlentities(stripslashes($row['id']));
$row_set[] = $new_row; //build an array
}
}
echo json_encode($row_set); //format the array into json data
}
Controller (relevant functions)
function signin() {
$this->load->helper("form");
$this->template->javascript('assets/js/underscore-min.js');
$this->template->javascript('assets/js/typeahead.min.js');
$data = $this->_currentMeeting();
$data['title'] = "Sign Someone In";
$data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
$data['mode'] = 'signin';
$this->load->view("home/attendance/signinout", $data);
}
function signout() {
$this->load->helper("form");
$this->template->javascript('assets/js/underscore-min.js');
$this->template->javascript('assets/js/typeahead.min.js');
$data = $this->_currentMeeting();
$data['attributes_form'] = array('id' => 'signInOutForm','class' => 'form-horizontal validate', 'enctype' => 'multipart/form-data');
$data['id'] = '';
$data['title'] = "Sign Someone Out";
$data['mode'] = 'signout';
$this->load->view("home/attendance/signinout", $data);
}
function get_people() {
$this->config->set_item('disable_template', TRUE);
$this->load->model('People_model');
$name = $this->input->post('query');
$this->People_model->get_person($name);
}
function dosigninout() {
$mode = $this->uri->segment(3);
switch($mode) {
case 'signin':
$mode = 'enter';
break;
case 'signout':
$mode = 'exit';
break;
default:
$this->load->view("home/error", array('error' => "Invalid mode specified."));
}
$meeting = $this->_currentMeeting();
$person = $this->input->post('person_id');
if(!$this->_validPerson($person, $this->input->post('person_name'))) $this->load->view("home/error", array('error' => "You requested an operation with ".$this->input->post('person_name')." who has an ID of $person. The name and ID don't match."));
$this->db->insert("attendance", array('person_id' => $person, 'meeting_id' => $meeting['meetingID'], 'type' => $mode));
$this->db->where("id", $person);
$this->db->update("people", array('status' => $mode));
$redirectTo = (isset($_POST['redirect'])) ? $this->input->post('redirect') : false;
if($redirectTo) redirect($redirectTo);
else redirect('attendance');
}
View
<?php
$baseURL = base_url();
$extraHeadData = "";
?>
<h2><?=$title?></h2>
<p>Current meeting: <?=$meetingTitle?> on <?=$meetingDate?>.</p>
<?=form_open("attendance/dosigninout/$mode", array('id' => "signInOutForm",'class' => "form-horizontal validate"))?>
<input type="hidden" name="person_id" id="person_id">
<?php echo validation_errors(); ?>
<fieldset>
<legend>Whom do you want to sign <?=($mode == "signin") ? 'in' : 'out'?>?</legend>
<div class="control-group">
<div class="controls">
<input type="text" placeholder="person's full name" name="person_name" id="person_name" class="person-typeahead">
</div>
</div>
</fieldset>
<div class="form-actions">
<?=form_submit('','Save changes','class="btn btn-primary"'); ?>
</div>
</form>
<script>
var person_url="<?php echo site_url('attendance/get_people')."/".$mode;?>";
$(function($) {
_.compile = function(templ) {
var compiled = this.template(templ);
compiled.render = function(ctx) {
return this(ctx);
}
return compiled;
}
$('.person-typeahead').typeahead({
template: '<p><strong><%= name %></strong>: <%= id %></p>',
name: 'people',
valueKey: 'name',
engine: _,
remote: (person_url),
dataType: 'json'
}).on('typeahead:selected typeahead:autocompleted', function(event, datum) {
$('#person_id').val(datum.id);
$('#person_name').val(datum.name);
});
});
</script>
<?=jquery_validate('attendance/signout');?>

Categories