i want to update my array data from table monitordata, but the data wont update i dont know where's the problem. there's no error in this code too :(
this is my controller
public function ubah($id) {
$data_lama = $this->monitor_m->get($id);
$this->data->tglmonitor = $data_lama->tglmonitor;
$this->data->detail = $this->monitor_m->get_record(array('monitor_data.idMonitor'=>$id),true);
$this->template->set_judul('SMIB | Monitoring')
->render('monitor_edit',$this->data);
}
public function ubahku($id) {
$id = $this->input->post('idMonitor_data');
if($this->input->post('idinven')!=NULL){
$idMonitor = $this->input->post('idMonitor');
$kondisi = $this->input->post('kondisi');
$nobrg = $this->input->post('nobrg');
$keterangan = $this->input->post('keterangan');
$kdinven = $this->input->post('kdinven');
$idinven = $_POST['idinven'];
for($i = 0; $i < count($idinven); $i++){
$data_detail = array(
'idMonitor' => $this->input->post('idMonitor'),
'idinven'=> $idinven[$i],
'kdinven'=> $kdinven[$i],
'nobrg'=> $nobrg[$i],
'kondisi'=> $kondisi[$i],
'keterangan' => $keterangan[$i]);
//print_r($data_detail);
$where = array('idMonitor_data' => $id);
$this->monitordata_m->update_by($where,$data_detail);
}
} redirect('monitorcoba');
}
This is my model monitordata_m
class Monitordata_m extends MY_Model {
public function __construct(){
parent::__construct();
parent::set_table('monitor_data','idMonitor_data');
}
This is MY_Model model i put in core folder.
public function update_by($where = array(), $data = array()) {
$this->db->where($where);
if ($this->db->update($this->table,$data)){
return true;
}
return false;
}
And this is my view
<?php echo form_open(site_url("monitorcoba/ubahku"),'data-ajax="false"'); ?>
<input data-theme="e" style="float: right;" data-mini="true" data-inline="false" data-icon="check" data-iconpos="right" value="Simpan" type="submit" />
<div data-role="collapsible-set" data-mini="true">
<?php foreach ($detail as $items): ?>
<div data-role="collapsible">
<?php echo form_hidden('idMonitor_data', $items['idMonitor_data'] ); ?>
<?php echo form_hidden('idMonitor', $items['idMonitor'] ); ?>
<h4><?php echo '[ '.$items['kdinven'].' ] '.$items['namabrg'] ?> </h4>
<?php echo form_hidden('kdinven', $items['kdinven'] ); ?>
<?php echo form_hidden('idinven', $items['idinven'] ); ?>
<div data-role="controlgroup">
<?php echo form_label ('Kondisi : ');
echo " <select name='kondisi' data-mini='true'>
<option value=".$items['kondisi'].">".$items['kondisi']."</option>
<option value=''>--Pilih--</option>
<option value='Baik'>Baik</option>
<option value='Rusak'>Rusak</option>
<option value='Hilang'>Hilang</option>";
echo "</select>";
echo form_input('keterangan',#$keterangan,'placeholder="Masukan Keterangan Tambahan"','class="input-text"');
?>
<?php echo form_close(); ?>
even if i use update_by it doesnt work. it's been 2 weeks and i have no clue :( i've tried all of the answer that i found in google but still.. so please help me.
This is the DATABASE result and POST_DATA for method ubahku
You have defined a method named update_by, but you are calling $this->monitordata_m->update($id,$data_detail);. Definitely it should not work. please call $this->monitordata_m->update_by($id,$data_detail); from your controller & check what will happen.
Firstly, Please correction $this->monitordata_m->update($id,$data_detail); to $this->monitordata_m->update_by($id,$data_detail); because your function name is update_by in your monitordata_m model.
Secondly, in your monitordata_m model update_by function have 2 param like $where = array() $data = array(), $where is a array but you calling in controller only $id. Your $id is not array. $where is like that $where = array('id' => $id) //id is where field name from db table
So, ubahku($id) method in your controller call $where in update_by function:
$where = array('id' => $id); // 'id' means "where field name"
$this->monitordata_m->update_by($where,$data_detail);
So, thank you so much for everyone who answer my question. so the problem was when i update the data, system only detect "kondisi[]" and "keterangan[]" as an array because i use this "[]" for both of it, so i just have to add "[]" in the end of every name in html form / views. so system will detect every input as an array. i hope you understand what i'm saying, sorry for my bad english. thank you this case is closed :)
Related
I am new to CodeIgniter and the HMVC framework and I am creating a sample test image dropdown in order to get a blueprint on how to solve the big project that I have on due this week. My question is, how can I able to search and display the filtered database values in a table format by using a dropdown list? For example, If I select on one of the values in the dropdown list and click search, all of the retrieved values will be filtered and will display according to the value selected in the dropdown list. Here is the code for the sample test code for the image dropdown:
Here is the code in my model:
class Image_model extends CI_Model{
function __construct(){
parent::__construct();
}
/*Sample test model function for the image dropdown list*/
//display the images table
public function displayTableImages()
{
$query = $this->db->select('main_image, main_image_url');
$query = $this->db->from('product_master');
$query = $this->db->get();
return $query->result();
}
//dropdown search list for images
public function searchDropdownImages($type)
{
switch ($type) {
case 'all':
{
$query = $this->db->where("main_image != '', 'main_image_url != ''");
}
case 'with-image':
{
$query = $this->db->where("'main_image != '', 'main_image_url != ''");
}
break;
case 'no-image':
{
$query = $this->db->where("'main_image = ''", "'main_image_url = ''");
}
break;
default:
$query = $this->db->select('main_image', 'main_image_url');
$query = $this->db->from('product_master');
break;
if ($query->num_rows()) {
return $query->result();
}
}
}
/*End sample test function*/
}
Here is the code for my controller:
if(! defined('BASEPATH')) exit('No direct script access allowed');
class Sample_image_dropdown extends MX_Controller{
public function __construct()
{
parent::__construct();
}
public function index()
{
$data['main_view'] = 'sample_view/image_dropdown_view';
$this->display_table_images();
}
public function display_table_images()
{
$this->load->model('Sample_model/image_model');
$data['images'] = $this->image_model->displayTableImages();
$data['main_view'] = 'sample_view/image_dropdown_view';
$this->load->view('sample_view/image_dropdown_view', $data);
}
public function search_dropdown_images($type)
{
$this->load->model('Sample_model/image_model');
$type['dropdown_images'] = $this->input->post('type');
switch ($type) {
case 'all':
$data['images'] = $this->image_model->get('all');
break;
case 'with-image':
$data['images'] = $this->image_model->get('with-image');
break;
case 'no-image':
$data['images'] = $this->image_model->get('no-image');
break;
default:
echo 'There are no images to be returned';
break;
}
$this->load->view('sample_view/image_dropdown_view', $type);
}
}
Here is the code in my view:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>
<div>
<?php echo "<select name='type' id='type'>
<option value='all'>All Image</option>
<option value='with-image'>With Image</option>
<option value='no-image'>Without Image</option>
</select>" ?>
<?php echo "<input type='submit' value='Search'>"; ?>
</div>
<div>
<h3>Images</h3>
</div>
<div>
<?php if (isset($images)): ?>
<?php foreach($images as $image): ?>
<table border="1">
<tr>
<td><?php echo "$image->main_image"; ?></td>
<td><?php echo "$image->main_image_url"; ?></td>
</tr>
</table>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
</body>
</html>
I will gladly appreciate any help/suggestion you can provide with regards to my question.
You should use AJAX for this.
First, you have to send a Query from ajax to call controller then Use the controller to load data from the database and Send it as an HTML block to the view and display it.
And also make an OnChange event to the drop-down linked to the ajax
Hope this one could help you
Use pagination library and get method to filter your data...
get method will help you to create base_url.
All you need to do is use your get data in for where statement. the problem you face is when you go to another page you lost your selected option.
in controller
after writing hole thing just change base_url for configure pagination and set it to
if(isset($_GET))
{
$config['first_url'] = $config['base_url'].'/1'.'?'.http_build_query($_GET, '', "&");
}
it will help to generate proper link
and at your view side .. get the selected value for the selected options..
<select name='type' id='type'>
<option value='all' <?php echo (isset($_get['type']) && $_get['type'] == 'with-image')?'selected':''; ?> >
All Image
</option>
<option value='with-image' <?php echo (isset($_get['type']) && $_get['type'] == 'with-image')?'selected':''; ?> >
With Image
</option>
<option value='no-image' <?php echo (isset($_get['type']) && $_get['type'] == 'no-image')?'selected':''; ?> >
Without Image
</option>
</select>
I have an array that looks like this
Array ( [0] => test1 [1] => test4 [2] => test2 )
I got this value from my database using Codeigniter built-in function
And whenever I try to insert this value back in my database, it's inserting the index instead of the value itself
The error I'm getting is
As you can see, instead of storing test1, test4, test2 in the fields under username, it is storing the index which are 0, 1, 2.
How to fix this please?
References:
#MichaelK
TABLE:
Project Table
User Table
Project-User Table
VIEW
<div class="panel-body">
<?php echo form_open('admin/add_recommended'); ?>
<div class="form-group col-lg-12">
<label>Recommended Employees:</label>
<?php echo form_error('skillsRequired'); ?>
<?php
foreach ($users as $row) {
$user[] = $row->username;
}
print_r($user);
echo form_multiselect('user[]', $user, $user, array('class' => 'chosen-select', 'multiple style' => 'width:100%;'));
?>
</div>
</div>
<div class="panel-footer">
<?php echo form_submit(array('id' => 'success-btn', 'value' => 'Submit', 'class' => 'btn')); ?>
<?php echo form_close(); ?>
</div>
CONTROLLER
public function add_recommended() {
$this->form_validation->set_rules('skillsRequired', 'Skills Required', 'min_length[1]|max_length[55]');
$lid = $this->admin_model->getID();
foreach ($lid as $id) {
$last_id = $id['projectID'];
$data['users'] = $this->admin_model->getUsers($last_id);
}
$this->load->view('admin/projects/rec-employee', $data);
if ($this->form_validation->run() === FALSE) {
//$this->load->view('admin/projects/rec-employee');
} else {
$users = $this->input->post('user');
print_r($users);
foreach ($users as $user) {
$data = array(
'projectID' => $last_id,
'username' => $user
);
$id = $this->admin_model->insert('projectemp', $data);
}
if ($id) {
$this->session->set_flashdata('msg', '<div class="alert alert-success" role="alert">Success! New Project has been added.</div>');
redirect('admin/add_recommended');
}
}
}
RENDERED VIEW
why you use $data['users'] in controller. Where $users contains index value. You try this
//CONTROLLER
$data = $this->admin_model->getUsers($last_id); //last id is the latest id.
//VIEW
foreach ($data as $row) {
$user[] = $row->username;
}
Boy these are too many comments for a small problem.
First of all #blakcat7, I hope you won't mind If I suggest a little change in your DB Schema. Use indexes and proper normalization it always helps. I have simulated your case on my machine.
It is your user table, I have added an ID with in this table.
Its your project table, just changed some field names, you can use your own
This is your table to create your join, Although you could have used user_id or posted_by field in projects table which could solve your problem too
Now Where i see it, you have users in your database table, you also have added projects but now you want to assign or associate that project with the user.
Make it simple just create a view where you can see both projects and users
Rendered by the Controller function
public function assignProject()
{
$data['projects']=$this->admin_model->getAll('projects');
$data['users']=$this->admin_model->getAll('user');
if($_POST)
{
$this->admin_model->assignUser($_POST);
$data['success']='User Assigned';
$this->load->view('assignProjects',$data);
}
else
{
$this->load->view('assignProjects',$data);
}
}
The view rendered by following markup
<form action="" method="post">
<div class="form-group">
<label>Project</label>
<select name="project" class="form-control">
<?php for($i=0;$i<count($projects);$i++){?>
<option value="<?php echo $projects[$i]['id']?>"><?php echo $projects[$i]['title']?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<label>Users</label>
<select name="user" class="form-control">
<?php for($i=0;$i<count($users);$i++){?>
<option value="<?php echo $users[$i]['id']?>"><?php echo $users[$i]['username']?></option>
<?php }?>
</select>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Assing User</button>
</div>
</form>
Just hit Assign User and the following function in the Model will save it in the project-user table
public function assignUser($data)
{
$record=array(
'user_id'=>$data['user'],
'project_id'=>$data['project'],
);
$this->db->insert('user_projects',$record);
}
Remember, always use an Index (ID) field in your tables, would make your DB iteration life simpler
OKAY EVERYONE, THANKS Y'ALL FOR YOUR HELP. IT REALLY MEANS SO MUCH TO ME. AFTER LIKE 2 DAYS OF STRUGGLE I FINALLY FIXED MY PROBLEM. ^_^
Special thanks to Michael K for helping me point out the problem and Malik Mudassar for giving me the idea how to do it.
Controller
public function add_recommended() {
$lid = $this->admin_model->getID();
foreach ($lid as $id) {
$last_id = $id['projectID'];
}
$data['users'] = $this->admin_model->getUsers($last_id);
$this->load->view('admin/projects/rec-employee', $data);
if ($_POST) {
$users = $this->input->post('recommended');
foreach ($users as $user):
$data = array(
'projectID' => $last_id,
'userID' => $user
);
$id = $this->admin_model->insertRecEmp($data);
endforeach;
$this->session->set_flashdata('msg', '<div class="alert alert-success" role="alert">Success! New Project has been added.</div>');
redirect('admin/add_project');
}
}
Model
public function getUsers($id) {
$this->db->select('*');
$this->db->from('users_skills e');
$this->db->join('projects_skills p', 'e.skillsID = p.skillsID');
$this->db->join('users u', 'u.userID = e.userID');
$this->db->where('p.projectID', $id);
$this->db->group_by('e.userID');
$this->db->order_by('e.percentage', 'desc');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$result[] = $row;
}
return $result;
}
return false;
}
public function getID() {
$this->db->select_max('projectID');
$this->db->from('projects');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
public function insertRecEmp() {
$this->db->insert('projects_users', $data);
}
View
<form action="add_recommended" method="post">
<select name="recommended[]" class="chosen-select" multiple title='Select Skills' multiple style="width: 100%;">
<?php for ($i = 0; $i < count($users); $i++) { ?>
<option value="<?php echo $users[$i]->userID ?>"><?php echo $users[$i]->username ?></option>
<?php } ?>
</select>
</form>
I completely changed my database and my PHP function for multi select
I´ve been trying this to work but seems isn´t going anywhere.
The problem is, the data doesn´t show in the View as a combobox it displays this error;
A PHP Error was encountered Severity: Notice Message: Undefined property: stdClass::$Campus Filename: views/energy_search_campus.php Line Number: 28 " >c_name.
So dunno where the problem should be... in the model, view, controller or even the db. Thanks in advance.
Model:
function campus_finder()
{
$this->db->group_by('campus');
$this->db->order_by('faculty', 'asc');
$query = $this->db->get('cpanel_energy');
if($query->num_rows()>0) {
foreach($query->result() as $row) {
$services[$row->id] = $row;
}
return $services;
}
}
View:
<div class="finder">
<div>
<label>Campus</label>
</div>
<select
id="campus"
name="campus"
class="form-control"
>
<option value="">----</option>
<?php foreach($catalogue as $item): ?>
<option value="<?php echo $item->Campus; ?>"
<?php if($campus) echo ($item->campus==$campus)? 'selected' : ''; ?>
><?php echo $item->campus; ?></option>
<?php endforeach; ?>
</select>
</div>
Controller:
function campus_search()
{
$submit = $this->input->post('send');
$campus = $this->input->post('campus');
$year = $this->input->post('year');
if($submit=='goback')
{
redirect("energy/catalogue/");
}
else
{
$data['catalogue'] = $this->model_energy_consumption->campus_finder();
$data['voucher'] = $this->model_energy_consumption->results_campus();
$data['services'] = $this->modelo_energy_consumption->services_catalogue_campus();
$data['campus'] = $campus;
$data['year'] = $year;
DB:
MAINTENANCE_JOB_ITEMS
|----|---------|---------|--------|
| id | account | faculty | campus |
|----|---------|---------|--------|
1 898946 f_name c_name
In the model you are returned $services , but the values are saved in $servicios variable
first call select function to select some record then group them
like this :
$this->db->select('user_id, first_name,last_name');
I'm working with CodeIgniter.
I need to get some data from database with a foreach loop.
I have 4 items in the database, but the loop retrieve only two of them (the items with id 2 and 4).
This is the code in the for the foreach in the controller:
$this->load->model('home_model');
$data['query']=$this->home_model->get_films($limit);
if ($data['query']) {
$data['main_content'] = 'home';
$data['film'] = array();
foreach($data['query'] as $film_info) {
$data['film'] = array(
'id' => $film_info->id,
'poster_src' => $film_info->film_poster_src,
'title' => $film_info->film_name,
'year' => $film_info->film_year,
'genre_id' => $film_info->genre_id,
);
$this->db->select('*');
$this->db->from('genres');
$this->db->where('id', $film_info->genre_id);
$query1 = $this->db->get();
$genre_info = $query1->row();
$data['genre_name'] = $genre_info->genre_name;
$this->db->select('*');
$this->db->from('votes');
$this->db->where('film_id', $film_info->id);
$this->db->where('vote', '1');
$query2 = $this->db->get();
$data['votes_count'] = $query2->num_rows();
}
$this->load->view('template', $data);
This is the code in the model:
<?php
class Home_model extends CI_Model
{
function get_films($limit)
{
$query = $this->db->get('films', $limit, $this->uri->segment(2));
return $query->result();
}
}
And this is the code in the view:
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="<?php echo $film['poster_src'] ?>" alt="Film poster">
<div class="caption">
<h3><?php echo $film['title'] ?></h3>
<p>Year: <?php echo $film['year'] ?></p>
<p>Genre: <?php echo $genre_name ?></p>
<p>Votes: <?php echo $votes_count ?></p>
<p>Watch Add to bookmarks</p>
</div>
</div>
</div>
If I put the foreach code in the view, it works properly.
I am not 100% sure so don't vote if false just make me aware i will try another way if possible.in foreach loop try to put the data in another array like this
$new_array[] = $the_result_value_you want
then you will be able to use $new_array outside the loop
I have been trying to find a solution to something that I believe is rather simple? What I would like to do is create a tabular form to collect some records for a survey.
Table: survey_record
id
meter_id
status_id
create_time
create_user
Table: survey_inspection
id
survey_record_id (FK)
bay_id
bay_usage_id
So table survey_inspection HAS_MANY inspections from survey_record.
Assuming an inspector is doing a survey for meter_id = 1001, the user identifies the status_id of the meter then, they have to fill in 4 inspection entries, as 1001 has 4 bays.
To generate the 4 bays I simply created a for loop. Which works fine.
View: _form.php
...
$meter=Meter::model()->findByPk($model->meter_id);
$bays = count($meter->bays); //retrieves the number of inspections required
<?php echo $form->dropDownListRow($model,'status_id',$model->getStatusId(),array('prompt'=>'Select Status ...')); ?>
...
<?php for ($i = 1; $i <= $bays; $i++): ?>
<?php echo $form->textFieldRow($inspection, "[$i]bay_id", array('readonly'=>true, 'value'=>"$i", 'class'=>'span1')); ?>
<?php echo $form->dropDownListRow($inspection, "[$i]bay_usage_id", $inspection->getUsageId(), array('prompt'=>'Bay Status ...') ); ?>
<?php endfor; ?>
...
However when I submit the form I am only receiving two (not four) results and I can't seem to display the validated fields correctly. So here's the famous controller file:SurveyRecordController.php
public function actionCreate($survey_id, $meter_id)
{
$model=new SurveyRecord;
$inspection = new SurveyInspection;
$model->survey_id = (int)$survey_id;
$model->meter_id = (int)$meter_id;
if(isset($_POST['SurveyRecord'], $_POST['SurveyInspection']))
{
$model->attributes=$_POST['SurveyRecord'];
$valid= $model->validate();
$i=1;
foreach($_POST['SurveyInspection'][$i] as $inspection)
{
$inspection = new SurveyInspection;
$inspection->bay_id =$_POST['SurveyInspection'][$i]['bay_id'];
$inspection->bay_usage_id =$_POST['SurveyInspection'][$i]['bay_usage_id'];
$valid= $inspection->validate() && $valid;
echo '<br/><br/><br/><pre>';
print_r($_POST['SurveyInspection'][$i]);
echo '</pre>';
if($valid)
{
if($model->save(false))
{
$inspection->survey_record_id = $model->id;
$inspection->save(false);
$this->redirect(array('/meter'));
}
}
$i++;
//$inspection->attributes=$_POST['SurveyInspection'][$i];
}
}
$this->render('create',array(
'model'=>$model,
'inspection'=>$inspection,
));
}
I have a funny feeling that I may not be doing the foreach loop correctly as when I view the array $_POST['SurveyInspection'][$i] I am only returned with two entries when there should be four.
Some information that may be helpful:
PHP version: 5.4.14
Yii version: 1.1.13
PostgreSQL version: 9.1.9
Thank you kindly :)
To my knowledge i think for the validation u have bypassed the default validation by passing
false to save method (ex : $model->save(false)) and u are also using yii's validate function . I think u try removing the false parameter and just use save() for the validation issue
The foreach loop is wrong. You can make it proper and a bit cleaner:
foreach($_POST['SurveyInspection'] as $i => $value)
{
$inspection = new SurveyInspection;
$inspection->bay_id = $value['bay_id'];
$inspection->bay_usage_id = $value['bay_usage_id'];
...
$i++ is not needed, as foreach will loop every element.
I've taken a completely different approach, valuable suggestions are always welcome :)
Hope this will be helpful for some of you.
Controller:
public function actionCreate($survey_id, $meter_id)
{
$bays = $this->getBayCount($meter_id);
for ($i=1;$i<=$bays;$i++)
{
$model=new SurveyRecord;
$model->survey_id = (int)$survey_id;
$model->meter_id = (int)$meter_id;
${'inspection_'.$i} = new SurveyInspection($i);
if(isset($_POST['SurveyRecord'], $_POST["SurveyInspection"][$i]))
{
$model->attributes = $_POST['SurveyRecord'];
${'inspection_'.$i}->attributes = $_POST["SurveyInspection"][$i];
echo '<br/><br/><br/><pre>';
print_r(${'inspection_'.$i}->attributes);
echo '</pre>';
}
}
for ($i=1;$i<=$bays;$i++)
{
${'inspection_'.$i} = new SurveyInspection($i);
$inspection['inspection_'.$i] = ${'inspection_'.$i};
}
$this->render('create',array(
'inspection'=>$inspection,
'model'=>$model
));
}
View:
...
<div class="control">
<?php echo $form->dropDownListRow($model,'status_id',$model->getStatusId(),array('prompt'=>'Select Status ...')); ?>
<?php
$meter=Meter::model()->findByPk($model->meter_id);
$bays = count($meter->bays);
?>
<?php for ($i=1; $i<=$bays; $i++): ?>
<table>
<tr>
<td><?php echo $form->textFieldRow($inspection["inspection_$i"], "[$i]bay_id",
array('readonly'=>true, 'value'=>"$i", 'class'=>'span1')); ?></td>
<td><?php echo $form->dropDownListRow($inspection["inspection_$i"], "[$i]bay_usage_id", $inspection["inspection_$i"]->getUsageId(),
array('prompt'=>'Bay Status ...') ); ?></td>
</tr>
</table>
<?php endfor; ?>
</div>
...
Credit: http://yiiblog.info/blog/index.php/post/108/Rename+ACtiveRecord+$_POST+array's+Name+to+update+multimodels
Note: There's still some work to be done on the view/controller (doesn't seem to be able to select on $_POST for my dropdowns on second model), will post once I have fixed it.
Thanks for your help #PeterM and #Ninad for your input.