Codeigniter : how to update mulitiple record where id - php

I have been looking for ways but find suitable speckle. so, i have table product and I show along with his ID. and I put in a form. and when I press the update button then what had been updated in the form of their corresponding id.
my view :
<?php echo form_open('stock/updating_stock');?>
<div class="panel-body scroll-menu" style="margin-top:0px;height:170px;padding-top:5px;">
<?php foreach($critical_plus_warning as $data){?>
<input type="hidden" name="id_product[]" value="<?php echo $data->id_product;?>">
<h5 class="hidden-xs"><b><?php echo $data->product_name;?></b> <input type="text" class="pull-right" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stock?>">
<?php
$stock = $data->stocks;
if($stock < 10){
echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
}else{
echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
}
?>
</h5>
<h5 class="hidden-lg"><b><?php $limited_word = word_limiter($data->product_name,3); echo $limited_word; ?></b> <input class="pull-right" type="text" style="width:10%;margin-left:10px;text-align:center;" name="update_stock[]" value="<?php echo $data->stocks?>">
<?php
$stock = $data->stocks;
if($stock < 10){
echo "<label style='font-size:13px;' class='label label-danger pull-right'>$stock</label>";
}else{
echo "<label style='font-size:13px;' class='label label-warning pull-right'>$stock</label>";
}
?>
</h5>
<?php }?>
</div>
<div class="col-xs-12" style="margin-top:-5px;background-color:white;padding:6px;background-color:white;box-shadow:0px 0px 8px 0px #bababa;"><button type="submit" name="submit" class="btn btn-success">Save data</button></div>
<?php echo form_close();?>
and my controller :
function updating_stock(){
$id = $this->input->post('id_product');
$stok = $this->input->post('update_stock');
$user = $this->data['id'];
for($i=0;$i<count($id);$i++){
$data = array(
array(
'id' => $id,
'stok' => $stok,
'diubah' => $user,
'tgl_diubah'=> date('Y:m:d H:i:s'),
),
);
}
//print_r($data);
$this->stok_adm->update_stok($data);
}
and my models :
function update_stok($data){
$this->db->update_batch($this->table, $data,'id_product');
return $this->db->affected_rows();
}

You need a where clause:
$this->db->where('id', $id);
...I think.

Try this:
Controller
function updating_stock(){
$id = $this->input->post('id_product');
$stok = $this->input->post('update_stock');
$user = $this->data['id'];
for($i=0;$i<count($id);$i++){
$data = array(
array(
'id' => $id,
'stok' => $stok,
'diubah' => $user,
'tgl_diubah'=> date('Y:m:d H:i:s'),
),
);
}
//print_r($data);
$this->stok_adm->update_stok($data,$id);
}
Model:
function update_stok($data,$id){
$this->db->update_batch($this->table, $data,'id_product');
return $this->db->affected_rows();
}

I think in your example update_batch will generate incorrect query beacues you need to update each record in db instead of updating them together - update_batch replaces values in multiple rows which fulfills conditions so there is possibility to update also incorrect rows (check example in documentation). So better idea is to update each single product using it's ID. It could look like that:
Model
function update_stok($data, $id_product){
$this->db->where('id_product', $id_product);
return $this->db->update($this->table, $data);
}
Controller
function updating_stock(){
$ids = $this->input->post('id_product');
$stok = $this->input->post('update_stock');
$user = $this->data['id'];
foreach($ids as $key => $id_product) {
$data = array(
'stok' => $stok[$key],
'diubah' => $user,
'tgl_diubah'=> date('Y:m:d H:i:s'),
);
$this->stok_adm->update_stok($data, $id_product);
}
}

$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name 2' ,
'date' => 'My date 2'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name 2' ,
'date' => 'Another date 2'
)
);
$this->db->update_batch('mytable', $data, 'title');
http://www.codeigniter.com/user_guide/database/query_builder.html?highlight=update_batch

Related

Displaying values in select box dynamically is not working in codeigniter

I am trying to get values in select box as dynamic is not working
here is the my controller code below:
public function CreateNewAsset()
{
$data['courselist'] = $this->Dashboard_model->getDashboardCourses();
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
//Validating Name Field
$this->form_validation->set_rules('topicname', 'Topicname', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('template/header');
$this->load->view('Dashboard/CreateNewAsset');
$this->load->view('template/footer');
} else {
//Setting values for tabel columns
$data = array(
'courseid' => $this->input->post('courseid'),
'topicname' => $this->input->post('topicname'),
'refid' => $this->input->post('refid'),
'startdate' => $this->input->post('startdate'),
'expectedend' => $this->input->post('expectedend')
);
//Transfering data to Model
$this->Dashboard_model->assetInsert($data);
$data['message'] = 'Data Inserted Successfully';
//Loading View
$this->load->view('template/header');
$this->load->view('Dashboard/CreateNewAsset', $data);
$this->load->view('template/footer');
}
}
Here is the my view below:
<form action="<?php echo base_url();?>Dashboard/CreateNewAsset" method="post">
<div class="form-row">
<div class="col-md-3">Course:</div>
<div class="col-md-9">
<select name="courseid" class="form-control">
<option value="0">Select Course</option>
<?php foreach ($courselist as $course) { ?>
<option value="<?php echo $course->id; ?>"><?php echo $course->coursename; ?></option>
<?php } ?>
</select>
</div>
</div>
</form>
I have added both getting values and insert in the same function. is this the problem I am not getting values in drop-down can anyone help me what is the mistake
and I am getting an error as Undefined variable: courselist
Change the insert part like this since u overriding $data:
$insert_data = array(
'courseid' => $this->input->post('courseid'),
'topicname' => $this->input->post('topicname'),
'refid' => $this->input->post('refid'),
'startdate' => $this->input->post('startdate'),
'expectedend' => $this->input->post('expectedend')
);
$this->Dashboard_model->assetInsert($insert_data);
The whole code should be like this :
NOTE : make sure u have loaded form_validation library and method getDashboardCourses return some data
public function CreateNewAsset()
{
$data['courselist'] = $this->Dashboard_model->getDashboardCourses();
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('topicname', 'Topicname', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('template/header');
$this->load->view('Dashboard/CreateNewAsset',$data);
$this->load->view('template/footer');
}
else
{
$insert_data = array(
'courseid' => $this->input->post('courseid'),
'topicname' => $this->input->post('topicname'),
'refid' => $this->input->post('refid'),
'startdate' => $this->input->post('startdate'),
'expectedend' => $this->input->post('expectedend')
);
$this->Dashboard_model->assetInsert($insert_data);
$data['message'] = 'Data Inserted Successfully';
$this->load->view('template/header');
$this->load->view('Dashboard/CreateNewAsset', $data);
$this->load->view('template/footer');
}
}
Your "View" can't find the courseList variable.
You need to do add courseList to your data array before you pass it to the view with the form.
Eg:-
data['courseList'] = $this->getCourseList(); // Fetch the list of rows

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.

CakePHP: FormHelper not showing default values from associated model

We have two models which are related by a has and belongs to many (HABTM) relationship: Jobs, Tests. We are able to add/edit the relationships successfully (we know because they show up in the join table), but we can't get the existing values to appear in the view. The select/checkboxes (we've tried both) are always empty.
Here are the model relationships:
//Job.php
public $hasAndBelongsToMany = array (
'Test' => array (
'classname' => 'Test',
'foreignKey'=>'job_id',
'joinTable' => 'jobs_tests',
'associatedForeignKey' => 'test_id'
)
);
//Test.php
public $hasAndBelongsToMany = array(
'Job' => array(
'className'=> 'Job',
'joinTable'=>'jobs_tests',
'foreignKey' => 'test_id',
'associatedForeignKey'=> 'job_id'
)
);
Here is the /view/Jobs/edit.ctp
echo $this->Form->select('Test', $test_options, array('class'=>'form-control', 'multiple'=>'checkbox'));
//This is always empty (nothing selected/checked).
What are we doing wrong?
Update:
Here is the JobsController action:
public function admin_edit( $id=NULL ) {
$this->layout = 'admin';
if (!$id)
$this->redirect( array('controller'=>'jobs', 'action'=>'index'));
$this->loadModel('Company');
$companies = $this->Company->find('all');
$company_options = array();
foreach ($companies as $company) {
$company_options[ $company['Company']['id'] ] = $company['Company']['name'];
}
$this->set('company_options', $company_options);
$this->loadModel('Test');
$tests = $this->Test->find('all');
$tests_options = array();
foreach ($tests as $test) {
$test_options[ $test['Test']['id'] ] = $test['Test']['name'];
}
$this->set('test_options', $test_options);
$category_options = $this->Job->validCategories;
$this->set('category_options', $category_options);
if ($this->request->isPut() ) {
$data = $this->request->data;
//debug($data);exit;
$save = $this->Job->save( $data );
if ($save) {
$this->Session->setFlash('Job edited');
//$job = $this->Job->findById( $id );
} else {
$this->Session->setFlash('Error editting job');
}
}
$job = $this->Job->findById($id);
$this->request->data = $job;
$this->set('job', $job);
}
Here is the form in the admin_edit.ctp view:
<?php echo $this->Form->create('Job'); ?>
<fieldset>
<?php
echo $this->Form->input('id', array('type'=>'hidden'));
echo $this->Form->input('name', array('class'=>'form-control'));
echo $this->Form->input('email', array('class'=>'form-control'));
echo $this->Form->input('location', array('class'=>'form-control'));
echo '<label>Type</label>';
echo $this->Form->select('type', array('FT'=>'Full Time', 'PT'=>'Part Time', 'IN'=>'Internship'), array('empty'=>false, 'class'=>'form-control'));
echo '<label>Company</label>';
echo $this->Form->select('company_id', $company_options, array('class'=>'form-control'));
echo $this->Form->input('short_description', array('label' => 'Short Description', 'class'=>'form-control'));
echo $this->Form->input('full_description', array('type'=>'textarea', 'label' => 'Full Description', 'class'=>'form-control'));
echo $this->Form->input('is_private', array('label'=>'Is Private?', 'class'=>'form-control') );
echo '<label>Category</label>';
echo $this->Form->select('category', $category_options, array('class'=>'form-control'));
echo '<label>Tests</label>';
//echo $this->Form->select('Test.id', $test_options, array('class'=>'form-control', 'multiple'=>true));
$selected = array();
foreach ($job['Test'] as $test) {
$selected[]=$test['id'];
//$selected[ $test['id'] ] = $test['name'];
}
debug($selected);
echo $this->Form->input('Test', array('type'=>'select', 'options'=>$test_options, 'class'=>'form-control', 'multiple'=>'checkbox', 'selected'=>$selected));
?>
</fieldset>
<?php echo $this->Form->end(__('Submit')); ?>
PHEW! This was a stumper but the solution turned out to be simple... The values in $options['selected'] were strings (of numbers), which was confusing CakePHP. We converted them to ints using intval() and it works perfectly now, using all the original settings...
Here's the revised version of what is in the view (notice the intval()):
$selected = array();
foreach ($job['Test'] as $test) {
$selected[]= intval($test['id']);
}
echo $this->Form->input('Test', array('type'=>'select', 'options'=>$test_options, 'class'=>'form-control', 'multiple'=>'checkbox', 'selected'=>$selected));
Also, as a sidenote, this is evidence that pretty much everything that was challenged in the comments above works completely fine:
$options['selected'] does not need to be key=>value pairs.
The pattern we're using does not overwrite the request->data and passes the data to the form helper just fine.
non-camelCased variable names passed to the view ($some_variable_name) are still picked up correctly by the form helper.
Hopefully this comes in handy to someone else.
What if you pass set the default values using Model::find('list').
//controller
$this->set('test_options', $this->YourModel->find('list'));
//view
echo $this->Form->select('Test', $test_options, array('class'=>'form-control', 'multiple'=>'checkbox'));

issue validation startdate and enddate codeigniter

i want to validate startdate and endate codeigniter, if stardate > enddate, not saving in my database, or show error message
my controller like this
function buat_lagi() {
if ($this->input->post('IDKategori')) {
$this->MKalender->addEvents();
$id = $_POST[IDKategori];
$this->session->set_flashdata('message', 'Agenda Pimpinan baru telah dibuat !');
redirect('admin/kalenderkategori/lihat/' . $id . '', 'refresh');
} else {
$data['title'] = "Tambah Agenda Pimpinan";
$data['kategori'] = $this->MKalenderKategori->getKategoriDropDown();
$data['main'] = 'admin/kalender/kalender_buat_lagi';
$this->load->vars($data);
$this->load->view('layout/dashboard');
}
}
my model like this
function addEvents() {
$data = array(
'IDKategori' => $this->input->post('IDKategori'),
'TanggalMulai' => $this->input->post('TanggalMulai'),
'TanggalAkhir' => $this->input->post('TanggalAkhir'),
'judul' => $this->input->post('judul'),
'konten' => $this->input->post('konten'),
'create_by' => $_SESSION['username'],
);
$this->db->insert('kalender', $data);
}
my form like this
<form action="<?= base_url(); ?>index.php/admin/kalender/buat_lagi/" method="post" enctype="multipart/form-data" name="form" id="form">
<?php
echo "<label for='ptitle'>Kegiatan / Lokasi :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'judul', 'id' => 'ptitle', 'size' => 80);
echo form_input($data);
echo "<p><label for='long'>Uraian Kegiatan / Keterangan / Catatan :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'konten', 'rows' => '13', 'cols' => '60', 'style' => 'width: 60%');
echo form_textarea($data) . "</p>";
echo "<p><label for='ptitle'>Waktu Mulai :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'TanggalMulai', 'id' => 'basic_example_1');
echo form_input($data) . "</p>";
echo "<p><label for='ptitle'>Waktu Akhir :</label><br/>";
$data = array('class' => 'validate[required] text-input', 'name' => 'TanggalAkhir', 'id' => 'basic_example_2', 'onblur' => 'function compareDate()');
echo form_input($data) . "</p>";
echo form_hidden('IDKategori', $this->uri->segment(4));
echo form_submit('submit', 'Tambah Even');
?>
<input type="button" value="Kembali" onClick="javascript: history.go(-1)" />
how to validate my issue ??
You haven't given the format of your dates or even which the date fields are (keep in mind most of the users here speak primarily English) You also haven't stated if you want this check server side or client side. By the compare dates function called in your form I am assuming you want it at least client side, I would suggest though that form validation needs to be done server side as well. Client side is great for immediate notification to the user but it's useless for actually protecting input to the form server side.
jQuery for the client side (since I am not sure which field is which this is pseudo code:
function compareDate()
{
var startDate = Date.parse($("#startDate).val()");
var endDate = Date.parse($("#endDate).val()");
if(startDate>endDate)
{
alert("Your start date must be earlier than your end date.");
}
}
Codeigniter function (the callback should work but I haven't tested it.) You really only have to run the function on one of the date fields, you only want to return one error and it's irrelevant which you return it on since it's comparing the two.
//validation rule
$this->form_validtion->set_rules('endDate', 'End Date','trim|callback_compareDates');
function compareDates()
{
$start = strtotime($this->input->post('startDate'));
$end = strtotime($this->input->post('endDate'));
if($start > $end)
{
$this->form_validation->set_message('compareDates','Your start date must be earlier than your end date');
return false;
}

How do I assign a unique static string for each item generated in a for loop?

How do I assign unique static strings to a variable in a for loop? I'm trying assign a unique description and alt tag to a list of thumbnails. I have managed to get the loop to produce the thumbnails but I cannot work out how to assign unique values to each one based on the condition of the value. This is the for loop:
<?php
for ( $project=1; $project<=40; $project++ ) {
echo "
<a href=\"#\" class=\"thumb\">
<img src=\"images/thumbs/$project.jpg\" width=\"300\" height=\"140\" alt=\"$projectname\" title=\"$projectname\" />
<span class=\"client\">$projectname</span><span class=\"description\">$type</span>
</a>
";
}
?>
I tried this before the for loop but didn't work...
if ( $project = 1 ) {
$projectname = "client1";
$type = "Interactive Brochure Design";
}
else if ( $project = 2 ) {
$projectname = "client2";
$type = "Site Design";
}
if ( $project == 1 ) {
$projectname = "client1";
$type = "Interactive Brochure Design";
}
else if ( $project == 2 ) {
$projectname = "client2";
$type = "Site Design";
}
= sets a variable and doesnt compare. == compares
of course there are probably more elegant ways for your project...
You would usually begin with storing each project in an array, so you can easily loop through them. The values stored in the array could be objects of some "project" class, or an associative array, like this:
$projects = array(
array(
'name' => 'client1',
'type' => 'Interactive Brochure Design',
'filename' => 'client1.jpg',
),
array(
'name' => 'client2',
'type' => 'Site Design',
'filename' => 'client2.jpg',
),
);
foreach($projects as $project)
echo '
<a href="#" class="thumb">
<img src="images/thumbs/'.$project['filename'].'" width="300" height="140" alt="'.$project['name'].'" title="'.$project['name'].'" />
<span class="client">'.$project['name'].'</span><span class="description">'.$project['type'].'</span>
</a>
';
That's what arrays are there for. Something like:
$projects = array(
array('name' => 'client1', 'type' => 'Interactive Brochure Design'),
array('name' => 'client2', 'type' => 'Site Design'),
);
for ($n=0; $n<count($projects); ) {
$projectname = $projects[$n]['name'];
$type = $projects[$n]['type'];
$project = ++$n;
echo "
<a href=\"#\" class=\"thumb\">
<img src=\"images/thumbs/$project.jpg\" width=\"300\" height=\"140\" alt=\"$projectname\" title=\"$projectname\" />
<span class=\"client\">$projectname</span><span class=\"description\">$type</span>
</a>
";
}
Or you could also use foreach:
foreach ($projects as $project) {
echo '<div>name: ' . $project['name'] . '</div>
<div>type: ' . $project['type'] . '</div>';
}
See it on codepad

Categories