I'm using CodeIgniter and I have a form with a checkbox that allows the user to check and remove their uploaded photo.
In my controller I use if(isset($checked) == 1)
to check if the user wants to remove the photo. $photo_to_table
will set empty and pass to $this->tank_auth->update_user()
to perform db update, and set photo field to become empty in table. Otherwise, it will remain the same photo.
But in my code, whether I check it or not, when I click UPDATE
button, it keeps removing the photo, I wonder why is it happening?
Can someone please go through my code and give an advise?
Controller:
$user_id = $this->session->userdata('user_id');
$profile = $this->users->get_profile_by_id($user_id);
if(!empty($_FILES['photo']['name']))
{
//image upload process
}
else
{
$checked = $this->input->post('remove');
if(isset($checked) == 1)
{
$photo_to_table = '';
// here will do remove process to delete file in directory
}
else
{
$photo_to_table = $profile->photo;
}
}
if($this->form_validation->run()) { // validation ok
if(!is_null($data = $this->tank_auth->update_user(
$this->form_validation->set_value('name'),
$this->form_validation->set_value('country'),
$this->form_validation->set_value('website'),
$photo_to_table
)))
{
// success
$this->session->set_flashdata('msg', 'Profile has been updated');
redirect(current_url());
}
}
View:
<?php echo form_open_multipart($this->uri->uri_string()); ?>
<table border="0">
<?php
if(!empty($uphoto)){
?>
<tr>
<td>
<div>
<img src="<?php echo base_url().$userpath.$uphoto; ?>" />
</div>
<div>
<input id="remove" type="checkbox" name="remove">
<label for="remove">Remove photo</label>
</div>
</td>
</tr>
<?php
}
?>
Thanks.
What you need to do here is to change this line ...
if(isset($checked) == 1){
to
if((int) $checked == 1){
The reason is that the variable $checked will always be set whether its value is 1 or not. $checked = $this->input->post('remove');
will return NULL if the 'remove'
is not set in the POST data.
Please write proper value in your checkbox :-
<input id="remove" type="checkbox" name="remove">
Write some value then check it :-
for e.g :
<input id="remove" type="checkbox" name="remove" value="1">
In php :-
if($checked == 1) {
// do whatever u want
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With