I have a simple form that displays an image gallery along with title, image and date. My problem is with the image input.
Selecting a new one and submitting everything works fine but when I'm not selecting any image it saves blank data in the image field.
Is there a way to save the form with the image change being optional?
Controller Code
public function submitwedding()
{
if(isset($_POST['edit']) && $_POST['edit']=='EDIT')
{
move_uploaded_file($_FILES['avatar']['tmp_name'],'uploadimg/'.$_FILES['avatar']['name']);
$data = array('title'=>$_POST['edit1'],'avatar'=>$_FILES['avatar']['name'],'date'=>$_POST['date']);
$this->Dbfunction->updatedata('wedding',$data,$_POST['id']);
redirect(base_url().'index.php/admin/wedding');
}
}
Front End Coding
<tr>
<td width="25%" >Title</td>
<td></td>
<td width="70%"><input type="text" name="edit1" id="title" style="width:250px"class="form-control" value="<?php echo $row->title ?>"></td>
</tr>
<tr height="10px"></tr>
<tr>
<td width="25%" >image</td>
<td></td>
<td width="70%">
<input type="file" name="avatar" value="<?php echo $row->avatar;?> " id="avatar" size="20" /><img src="<?php echo base_url(); ?>uploadimg/<?php echo $row->avatar; ?>"/>
</td>
</tr>
<tr>
<td width="25%" >Date</td>
<td></td>
<td width="70%"><input type="text" name="date" id="date" style="width:250px"class="form-control" value="<?php echo $row->date ?>"></td>
</tr>
Dbfunction Coding
function selectdatabyid($table , $id)
{
$query = $this->db->query('select * from '.$table.' where id='.$id);
return $query->row();
}
function updatedata($table , $data , $id)
{
$this->db->where('id', $id);
$this->db->update($table, $data);
}
function deletedata($table, $id)
{
$this->db->where('id', $id);
$this->db->delete($table);
}
Why don't you leave the value=""
attribute for the image-form-tag empty? When the user submits without selecting a new picture to upload, don't update the field in the database.
Just add an if
into your php code:
if(!empty($_POST['avatar'])) {
// update avatar because input is not empty
}