I am trying to update specific row in tables using select options tag .But it is updating last inserted row only and not the specificed. I need solution.
controller:
public function user_status()
{
$this->load->model('customize_model');
$data = array("user_status" => $this->input->post('status'),
"user_id" => $this->input->post('user_id'));
$data1['user'] = $this->customize_model->update_status($data);
$this->load->view('custom/user',$data1);
}
Model:
public function update_status($data)
{
$user_id = $this->input->post('user_id');
$this->db->set($data);
$this->db->where('user_id',$user_id);
return $this->db->update('user',$data);
}
My View:
<?php
foreach($user->result() as $row)
{
?>
<tr>
<input type="hidden"
value="<?php echo $row->user_id; ?>"
name="user_id" />
<td><?php echo $row->user_id; ?></td>
<td><?php echo $row->user_status; ?></td>
<td>
<select name="status"
id="user_status">
<option value="Active">Active</option>
<option
value="Inactive">Inactive</option>
</select>
</td>
<td>
<button name="submit"
type="submit" value="<?php echo $row->user_id;?
>"> Update<?php echo $row->user_id;?></button>
</td>
</tr>
<?php
}
?>
CodePudding user response:
The problem here is the same name="user_id" is looped in your view along with other name attributes. So the last value is sent to the controller.
In View: Create two inputfields
<input type="hidden" name="global_userId" id="global_userId" />
<input type="hidden" name="global_status" id="global_status" />
Try setting the name and id as
name="status-<?php echo $row->user_id; ?>" id="status-<?php echo $row->user_id; ?>"
for all name attributes in loop. and make the button type button rather than submit and make it call function onclick. like
onClick="submitForm(<?php echo $row->user_id; ?>)"
and create the Jquery function to update the input field and submit the form:
function submitForm(userId){
$('#global_userId').val(userId);
var status = $('#status-' userId).val();
$('#global_status').val(status);
$('#formId').submit();
}
In controller and model accept the 'global_userId' and 'global_status' for the values.
$user_id = $this->input->post('global_userId');
