I have two fields one for link and one for file upload in form, how do i add only one of those i.e. either link or file in database,
Sorry for any wrong code and methods, I am a newbie here and this is my first question in stack overflow. Hope you all help me out.
My Controller is
public function add_scrolllink()
{
$this->form_validation->set_rules('stitle','File Title','trim|required');
$this->form_validation->set_rules('slink','File Link','trim|required');
if(empty($_FILES['sfile']['name']))
{
$this->form_validation->set_rules('slink','File Link','required');
}
if($this->form_validation->run() == FALSE)
{
$this->load->view("add_scrolllink");
}
else
{
$slink_id = $this->input->post('stitle');
$slink_files = $this->input->post('slink');
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'pdf|docx|doc';
$config['max_size'] = 9000;
$this->upload->initialize($config);
$this->load->library('upload',$config);
if(!$this->upload->do_upload('slink'))
{
$msg1 = $this->upload->display_errors();
header("Location:".base_url()."news/add_scrolllink?msg1=$msg1");
}
else
{
$output = $this->upload->data();
$file2 = $output['file_name'];
$this->load->model('mpages');
$output1 = $this->mpages->add_scrolllink($slink_title,$file2);
if($output1)
{
$msg = "Scrolling Link added successfully!";
header("Location:".base_url()."news/scrolllink_list?
msg=$msg");
}
else
{
$msg1 = 'Scrolling Link add failed. Try again!';
header("Location:".base_url()."news/add_scrolllink?
msg1=$msg1");
}
}
}
//My View is
<form action="<?php echo base_url(); ?>news/add_scrolllink" method="post"
role="form" enctype="multipart/form-data">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<div class="panel panel-default">
<div class="panel-body">
<div class="form-group">
<label>Scrolling Link Title</label>
<input type="text" name="stitle" class="form-
control" value="<?php echo set_value('stitle'); ?>" placeholder="Enter
Scrolling Link Title">
</div>
<style type="text/css">
p.help-block{color:#ff0000;}
</style>
<div class="form-group">
<label>Scrolling Link</label>
<input type="text" name="slink" class="form-control"
value="<?php echo set_value('slink'); ?>" placeholder="Enter Scrolling
Link">
</div>
OR ADD FILE TO SCROLL LINK
<div class="form-group">
<label>Choose File to Upload</label>
<input type="file" name="slink" class="form-
control">
</div>
<input type="submit" name="submit" class="btn btn-
primary" value="Add Link"><br>
<?php echo "<br><span
style='color:#ff0000;'>".validation_errors()."</span>"; ?>
<?php
if(isset($_GET['msg'])){
echo "<div class='alert alert-success
fadein'>".$_GET['msg']."</div>";
}
if(isset($_GET['msg1'])){
echo "<div class='alert alert-danger
fadein'>".$_GET['msg1']."</div>";
}
?>
</div>
</div>
</div>
<div class="col-md-2"></div>
<div class="clearfix"></div>
</div>
</form>
you have use jquery to get input box value using this code and set some condition
$('#slink-id').val(); // set link field input box id
$('#slinkFile-id').val(); //set upload file field id
if($('#slink-id').val() != '' && $('#slinkFile-id').val() == ''){
// setread only your file field
}else{
// set read only link field
}
Related
I have a weird problem, I'm doing upload an image using codeigniter, but the thing was weird. it save to the database but part of them can upload to the specific folder, and the other not. Can someone help me ? I'm using Codeigniter 3 and PHP 7.3.13
this is my controller :
public function edit_pegawai($id_pegawai){
if (isset($_POST['simpan'])){
$this->form_validation->set_rules('nama', 'Nama', 'required');
$data_pegawai=array(
'nik'=> $this->input->post('nik'),
'nama'=> $this->input->post('nama')
);
$data['dataPegawai'] = $data_pegawai;
if ($this->form_validation->run() == TRUE){
$img = $this->UserModel->get_foto($id_pegawai)->row();
$image = $img->foto;
if ($_FILES['foto']['name']){
if ($image != NULL){
unlink('./assets/img/foto/'.$image);
}
$nama = ucwords(strtolower($this->input->post('nama')));
$config['upload_path'] = './assets/img/foto/';
$config['allowed_types'] = 'jpe|jpg|jpeg';
$config['max_size'] = 10000;
$config['file_name'] = $nama;
$config['overwrite'] = TRUE;
$this->load->library('upload');
$this->upload->initialize($config);
if ($_FILES['foto']['type'] == 'image/jpeg' || $_FILES['foto']['type'] == 'image/png' || $_FILES['foto']['type'] != 'image/jpg'){
$this->upload->do_upload('foto');
$hilihh = $this->upload->data();
$foto = $hilihh['file_name'];
}
else{
$this->session->set_flashdata('msg_gagal');
redirect(site_url('listpegawai'));
}
$this->db->update('pns_local', $data_pegawai, array('id_pegawai'=>$id_pegawai));
$this->db->set('foto', $foto);
$this->db->where('id_pegawai', $id_pegawai);
$this->db->update('pns_local');
$this->session->set_flashdata('msg_berhasil');
redirect(site_url('listpegawai'));
}
and this is my view
<form method="POST" action="<?= site_url('listpegawai/edit_pegawai/'.$dataPegawai['id_pegawai'])?>" enctype="multipart/form-data">
<input hidden type="text" name="id_pegawai" value="<?php echo $dataPegawai['id_pegawai']; ?>">
<div class="card bg-light">
<div class="form-row">
<div class="form-group col-md-4">
<label>NIK </label>
<input type="text" class="form-control" name="nik" value="<?php echo $dataPegawai['nik'];?>">
</div>
<div class="form-group col-md-4">
<label>Nama Lengkap </label>
<input type="text" class="form-control" name="nama" value="<?php echo $dataPegawai['nama'];?>">
</div>
<div class="form-row">
<div class="form-group col-md-10">
<label>Foto <span style="color: red">*</span></label><br>
<?php
if ($dataPegawai['foto'] != NULL){
?>
<img src="<?php echo base_url('assets/img/foto/'.$dataPegawai['foto'])?>" width="85" height="100">
<?php }
else{
?>
<img src="<?php echo base_url('assets/img/foto/default.png')?>" width="85" height="100">
<?php }
?>
<span> <input type="file" name="foto" accept="image/*"></span>
</div>
</div>
<button type="submit" name="simpan" class="btn btn-primary btn-block">Simpan Data
</button>
</div>
</form>
Thankyou for your help
Set $config['log_threshold'] = 4; and see the CI logs in application/logs/
Php logs can also help.
In your controller try taking ./ out of your upload path
I'm trying to insert data into database through a form. I'm uploading 2 image files, in database path of the files will be stored. I'm trying to do server side validation. when user does not upload a file or when user is uploading wrong file type, an error messages should display and page should return to same page with no data inserted into database.
This is my view:
<div class="main-panel">
<div class="content-wrapper">
<div class="row">
<div class="col-md-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Add News & Event</h4>
<p class="card-description"> </p>
<?php echo validation_errors("<div class='alert alert-danger'>","</div>");?>
<?php if($failed = $this->session->flashdata('addNewsFailed')){
echo '<div class="alert alert-danger">' ;
echo $failed;
echo '</div>';
}?>
<form class="forms-sample" action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleInputName1">Title</label>
<input type="text" class="form-control" id="exampleInputName1" value="<?php echo
set_value("title");?>" name="title">
</div>
<div class="form-group">
<label for="exampleInputName1">Sub Title</label>
<input type="text" class="form-control" id="exampleInputName1" value="<?php echo set_value("sub");?>" name="sub_title">
</div>
<div class="form-group">
<label for="exampleInputName1">Event Date</label>
<input type="text" class="form-control" id="exampleInputName1" name="date" value="<?php echo date('d - M - y ');//echo set_value("date");?>">
</div>
<div class="container">
<div class="row">
<div class="col-md">
<div class="form-group">
<label>Feature Image</label>
<div class="input-group col-xs-12">
<input type="file" class="form-control file-upload-info" placeholder="Upload Image" name="img" style="z-index: 9999; opacity: 0;" id="image">
<div id="imageName"></div>
<span class="input-group-append">
<button class="file-upload-browse btn btn-info" type="button" style="position: absolute; left: 0; padding: 6px 23px;border-radius:3px;">Upload</button> </span>
</div>
<?php if(isset($upload_error)){
echo $upload_error;
}?>
</div>
</div>
<div class="col-md">
<div class="form-group">
<label> Banner Image</label>
<div class="input-group col-xs-12">
<input type="file" class="form-control file-upload-info" placeholder="Upload Image" name="banner" id="banner" style="opacity: 0; z-index: 9999;">
<div id="bannerName"></div>
<span class="input-group-append">
<button class="file-upload-browse btn btn-info" type="button" style="position: absolute;left: 0;padding: 6px 23px;border-radius: 3px;">Upload</button></span>
</div>
<?php if(isset($upload_error1)){
echo $upload_error1;
}?>
</div>
</div>
</div>
</div>
<span class="input-group-append">-->
<div class="form-group">
<label for="exampleTextarea1">Text</label>
<textarea class="form-control" id="exampleTextarea1" rows="2" name="para" value=""><?php echo set_value("para");?></textarea>
</div>
<button type="submit" class="btn btn-success mr-2">Add</button>
<button class="btn btn-light">Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
This is my controller:
public function addEvent()
{
//load library
$this->load->library('form_validation');
$this->load->helper('form');
//set rules for validation
$this->form_validation->set_rules("title", "Title", "required");
$this->form_validation->set_rules("date", "Event Date", "required");
$this->form_validation->set_rules("para", "Text", "required");
//template
$this->output->set_template('admin_layout');
//image upload
$config = [
'upload_path' => './uploads/',
'allowed_types' => 'gif|jpg|png',
];
$this->load->library('upload', $config);
//validation
if ($this->form_validation->run()) {
$post = $this->input->post();
if (!$this->upload->do_upload('img')) {
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/pages/forms/addEvent', compact('upload_error'));
} else {
$Feature1 = $this->upload->data();
$image_path = base_url('uploads/' . $Feature1['raw_name'] . $Feature1['file_ext']);
$post['image_path'] = $image_path;
}
if (!$this->upload->do_upload('banner')) {
$upload_error1 = $this->upload->display_errors();
$this->load->view('dashboard/pages/forms/addEvent', compact('upload_error1'));
} else {
$carsousel = $this->upload->data();
$banner = base_url('uploads/' . $carsousel['raw_name'] . $carsousel['file_ext']);
$post['banner'] = $banner;
}
$this->load->model('loginmodel', 'addNews');
$insert_id = $this->addNews->addNews($post);
if ($insert_id) {
$this->session->set_flashdata("addNewsSuccess", 'News & Event Added Successfully');
redirect('dashboard/update_news/' . $insert_id);
} else {
$this->session->set_flashdata("addNewsFailed", 'Failed');
$this->load->view('dashboard/pages/forms/addEvent');
}
} else {
$upload_error = $this->upload->display_errors();
$this->load->view('dashboard/pages/forms/addEvent', compact('upload_error'));
}
}
This is my model:
public function addNews($array)
{
$this->db->insert('news', $array);
return $this->db->insert_id();
}
My form validation are working perfectly but when user is uploading wrong file type or does not upload any file then file upload error message is not displaying and data is inserting into database the with both image field empty.
I created image upload which works fine but I also want it to be updated. When I add a need image it updates correctly but I if don't want to change the image and leave it as it is, then my current image can't be retrieve.i want to update my factory_name(field name) only sometimes. when i update image it updated successfully,but when i update factory_name only the existing image is missing. Please help me how to do this?
this my view file
<form action="<?php echo base_url('login/insert_factory/'.$id); ?>" method="POST" enctype="multipart/form-data">
<?php
$id =$this->uri->segment(3);
if($id == "")
{
?>
<div class="form-group">
<label class="form-label" for="field-1">Factory Name</label>
<!--span class="desc">e.g. "Beautiful Mind"</span-->
<div class="controls">
<input type="text" name="factory_name" class="form-control" >
</div>
</div>
<?php
}
else
{ ?>
<div class="form-group">
<label class="form-label" for="field-1">Factory Name</label>
<!--span class="desc">e.g. "Beautiful Mind"</span-->
<div class="controls">
<input type="text" name="factory_name" value="<?php echo $result->factory_name; ?>" class="form-control" >
</div>
</div>
<?php } ?>
<?php
if($id == "")
{
?>
<div class="form-group">
<label class="form-label" for="field-1">Upload Logo</label>
<!--span class="desc">e.g. "Beautiful Mind"</span-->
<div class="controls">
<input type="file" name="upload_logo" />
</div>
</div>
<?php
}
else
{ ?>
<div class="form-group">
<label class="form-label" for="field-1">Upload Logo</label>
<!--span class="desc">e.g. "Beautiful Mind"</span-->
<div class="controls">
<input type="file" name="upload_logo" value="<?php echo $result->factory_logo; ?>" />
</div>
</div>
<?php } ?>
<?php
if($id == "")
{
?>
<div class="form-group">
<div class="controls">
<input type="submit" class="btn btn-primary" value="submit" />
</div>
</div>
<?php
}
else
{ ?>
<div class="form-group">
<div class="controls">
<input type="submit" class="btn btn-primary" value="Update" />
</div>
</div>
<?php } ?>
</form>
this my controller code:
public function insert_factory()
{
$id =$this->uri->segment(3);
if($id == "")
{
if(isset($_FILES['upload_logo'])){
$errors= array();
$file_name = $_FILES['upload_logo']['name'];
$file_tmp =$_FILES['upload_logo']['tmp_name'];
if(empty($errors)==true){
move_uploaded_file($file_tmp,"assets/uploads/".$file_name);
// echo "Success";
}else{
print_r($errors);
}
$fields = array(
'factory_name' => $this->input->post('factory_name',True),
'factory_logo' => $file_name
);
$result = $this->login_model->insert_factory($fields);
if($result){
$this->session->set_flashdata('success_msg',' Factory Created Successfully!');
redirect('login/view_factory');
}else{
$this->session->set_flashdata('error_msg','Factory Cannot Created.!');
redirect('login/create_factory');
}
}
}else{
if(isset($_FILES['upload_logo'])){
$errors= array();
$file_name = $_FILES['upload_logo']['name'];
$file_tmp =$_FILES['upload_logo']['tmp_name'];
if(empty($errors)==true){
move_uploaded_file($file_tmp,"assets/uploads/".$file_name);
// echo "Success";
}else{
print_r($errors);
}
$fields = array(
'factory_name' => $this->input->post('factory_name',True),
'factory_logo' => $file_name
);
$this->db->where('factory_id', $id);
$this->db->update('create_factory', $fields);
if($this->db->affected_rows()>0)
{
$this->session->set_flashdata('success_msg',' Factory Updated Successfully!');
}else{
$this->session->set_flashdata('error_msg','Factory Cannot Updated.!');
redirect('login/create_factory');
}
redirect(base_url('login/view_factory'));
}
}
}
And this my model file:
public function insert_factory($fields)
{
$this->db->insert('create_factory',$fields);
return ($this->db->affected_rows() != 1) ? false : true;
}
In your controller, in both if and else blocks, please modify your existing code in order to not update empty image when image is not provided and only factory name is provided.
This code in both if and else blocks:
$fields = array(
'factory_name' => $this->input->post('factory_name',True),
'factory_logo' => $file_name
);
Needs to be change to:
$fields['factory_name'] = $this->input->post('factory_name', True);
if (!empty($file_name)) {
$fields['factory_logo'] = $file_name;
}
Here, my php script for upload image in server. i want user can upload multiple images on one records. right now, in this code at time only one image can post, user's requirement is they can post multiple images at time. I don't idea how can I possible using arrays. please help. Thanks in advance :)
<?php
include ("connect.php");
if(isset($_POST['submit']))
{
$event = $_POST['evnt_name'];
$image_name = $_FILES['evnt_img']['name'];
$image_type = $_FILES['evnt_img']['type'];
$image_size = $_FILES['evnt_img']['size'];
$image_tmp = $_FILES['evnt_img']['tmp_name'];
if($event=='' && $image_name==''){
echo "<script>alert('Any field is empty')</script>";
exit();
}
if($image_type=="image/jpeg" OR $image_type=="image/png" OR $image_type=="image/gif")
{
if($image_size<=50000)
{
move_uploaded_file($image_tmp,"imagess/$image_name");
}
else
{
echo "<script>alert('image is large, only 50kb size allowed')</script>";
exit();
}
}
else{
echo "<script>alert('image type is invalid')</script>";
exit();
}
$query = "insert into event_update (evnt_text,evnt_img) values ('$event','$image_name')";
if(mysqli_query($conn,$query))
{
echo "<script>alert('Post has been published')</script>";
exit();
}
}
?>
And below my simple bootstrap HTML code for form
<div class="col-lg-12">
<form method="POST" action="evntform.php" enctype="multipart/form-data">
<div class="form-group">
<label>Events Name</label>
<input type="text" name="evnt_name" placeholder="Write Events Name" class="form-control">
</div>
<div class="form-group">
<label>File input</label>
<input type="file" name="evnt_img[]">
</div>
<button name="submit" type="submit" class="btn btn-default">Submit Button</button>
</form>
</div>
Here is a quick example:
HTML:
<div class="col-lg-12">
<form method="POST" action="evntform.php" enctype="multipart/form-data">
<div class="form-group">
<label>Events Name</label>
<input type="text" name="evnt_name" placeholder="Write Events Name" class="form-control">
</div>
<div class="form-group">
<label>File input</label>
<input type="file" name="evnt_img[]" multiple>
</div>
<button name="submit" type="submit" class="btn btn-default">Submit Button</button>
</form>
PHP code to select the first image uploaded:
<?php
include ("connect.php");
if(isset($_POST['submit']))
{
$event = $_POST['evnt_name'];
$image_name = $_FILES['evnt_img'][0]['name'];
$image_type = $_FILES['evnt_img'][0]['type'];
$image_size = $_FILES['evnt_img'][0]['size'];
$image_tmp = $_FILES['evnt_img'][0]['tmp_name'];
....
You can use a for loop for every image:
for($i=0;$i<count($_FILES['evnt_img']);$i++){
$image_name = $_FILES['evnt_img'][$i]['name'];
}
J
controller
<?php
class Breaking extends MY_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('breaking_model');
}
public function create_breaking_news()
{
$this->securePage();
if ($this->input->post('submit')) {
$this->form_validation->set_rules('title', ' Breaking News Title', 'required');
$this->form_validation->set_rules('details', ' Breaking News Details', 'required');
if ($this->form_validation->run()) {
$added_on = time();
// if image is uploaded
if (isset($_FILES['userfile']['name']) && $_FILES['userfile']['size']>0) {
$config['upload_path'] = $this->config->item('upload_path');
$config['allowed_types'] = $this->config->item('allowed_types');
$config['max_size'] = $this->config->item('max_size');
$config['max_width'] = $this->config->item('max_width');
$config['max_height'] = $this->config->item('max_height');
$config['encrypt_name'] = $this->config->item('encrypt_name');
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$image = $this->upload->data();
$this->breaking_model->add_news($image['file_name'], $added_on);
$this->session->set_flashdata('msg', '<button class="btn btn-success" style="width:100%;">The Breaking News has been added successfully.</button>');
redirect('breaking/manage-breaking-news');
} else {
$this->session->set_flashdata('msg', $this->upload->display_errors());
redirect('breaking/create-breaking-news');
}
} else {
// if image is not uploaded
$this->breaking_model->add_news(null, $added_on);
$this->session->set_flashdata('msg', '<button class="btn btn-success" style="width:100%;">The About Breaking News been added successfully.</button>');
redirect('breaking/manage-breaking-news');
}
}
}
$data['news_title'] = 'Add Breaking news | Kanchan news.com';
$data['Keywords'] = '';
$data['url'] = '';
$data['content'] = $this->load->view('breaking/create', $data, true);
$this->load->view('kanchan', $data);
}
}
my models
function add_news($image, $added_on) {
$this->db->set('title', $this->input->post('title'));
$this->db->set('details', $this->input->post('details'));
$this->db->set('video', $this->input->post('video'));
$this->db->set('images', $image);
$this->db->set('added_on', $added_on);
$this->db->insert('breaking_news');
}
and my view
<div class="container">
<ol class="breadcrumb">
<li class="active"><?php echo $this->session->userdata('full_name');?></li>
<li class="active">Breaking News</li>
<li class="active">Add Breaking News</li>
</ol>
<?php echo $this->session->set_flashdata('msg');?>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title"> Enetr Breaking News Title :</label>
<hr>
<input type="text" name="title" class="form-control" value="<?php echo set_value('title');?>">
<?php echo form_error('title');?>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="title"> Enetr Breaking News Images :</label>
<hr>
<input type="file" name="userfile">
<?php echo form_error('userfile');?>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="title"> Enetr Breaking News Video Url( not required) :</label>
<hr>
<input type="video" name="video" class="form-control" value="<?php echo set_value('video');?>">
<?php echo form_error('video');?>
</div>
</div>
</div>
<div class="form-group">
<label for="title"> Enetr Breaking News Details :</label>
<hr>
<textarea class="ckeditor" name="details"><?php echo set_value('details');?></textarea>
<?php echo form_error('details');?>
</div>
<button class="btn btn-success" name="submit" value="submit" type="submit">Add Breaking News</button>
</form>
<hr>
</div>
i can add data without image successfully but when i select image it wont added data and redirect too create page without any error message and same problems with update too