Not able to insert image path into database in codeigniter - codeigniter

class Stud_controller extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->helper('url');
$this->load->database();
}
public function index()
{
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->helper('url');
$this->load->view('Stud_view',$data);
}
public function add_student_view()
{
$this->load->helper('form');
$this->load->view('Stud_add');
}
public function add_student()
{
$this->load->helper('form');
$this->load->library('form_validation');
$this->load->model('Stud_Model');
//$this->load->library('upload', $config);
$config['upload_path'] = './uploads/';
$target_file['image'] = $config['upload_path'] . basename($_FILES["fileToUpload"]["name"]);
$config['allowed_types'] = 'gif|jpg|jpeg|png|pdf|doc';
$config['max_size'] = 1000;
$config['max_width'] = 1300;
$config['max_height'] = 1024;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('fileToUpload'))
{
echo "fail";
//$this->load->view('upload', $error);
}
else
{
echo "success";
echo $target_file['image'] ;
//$QueryInsertFile="INSERT INTO stud SET image='$target_file'";
// $this->load->view('success', $data);
}
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name'),
$target_file['image'] =>$data['image']
);
$this->Stud_Model->insert($data);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function update_student_view(){
$this->load->helper('form');
$roll_no = $this->uri->segment('3');
$query = $this->db->get_where("stud",array("roll_no"=>$roll_no));
$data['records'] = $query->result();
$data['old_roll_no'] = $roll_no;
$this->load->view('Stud_edit',$data);
}
public function update_student(){
$this->load->model('Stud_Model');
$data = array(
'roll_no' => $this->input->post('roll_no'),
'name' => $this->input->post('name')
);
$old_roll_no = $this->input->post('old_roll_no');
$this->Stud_Model->update($data,$old_roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
public function delete_student(){
$this->load->model('Stud_Model');
$roll_no = $this->uri->segment('3');
$this->Stud_Model->delete($roll_no);
$query = $this->db->get("stud");
$data['records'] = $query->result();
$this->load->view('Stud_view',$data);
}
}

this line is error
$target_file['image'] =>$data['image']
replace into
'image'=>$_target_file['image]

Related

how to upload image and insert into database into codeigniter 3

i try to upload image and insert it into database but it's not working.
there is no any error showing in page and image is also not uploading or inserting into database,
please, give me a solution for that how can i solved this problem?
my code is here,
the code of controller is here, enter code here
public function add_product()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$input_name = "product_image";
if (!$this->upload->do_upload($input_name))
{
$data['items'] = $this->data_model->get_data_info('product_id','product');
$this->load->view('product',$data);
}
else
{
$image_info = $this->upload->data();
$data = array(
'product_name'=>$this->input->post('product'),
'product_pic'=>$image_info['file_name'],
'description'=>$this->input->post('description')
);
$query = $this->data_model->add_data($data,'product');
if($query == TRUE){
echo "product added";
$data['items'] = $this->data_model->get_data_info('product_id','product');
$this->load->view('product',$data);
}else{
echo"product already exists";
$data['items'] = $this->data_model->get_data_info('product_id','category');
$this->load->view('product',$data);
}
}
}
model :
public function add_data($data,$table){
$result = $this->db->get_where($table,$data);
$query = (bool)$result->num_rows();
if(!$query){
if($this->db->insert($table,$data)){
return TRUE;
}else{
return FALSE;
}
}else{
return FALSE;
}
}
controller code
function add_product() {
if (!is_dir('./Uploads/')) {
mkdir('./Uploads/', 0777, TRUE);
}
if (!empty($_FILES['product_image'])) {
$config['upload_path'] = './Uploads/';
$config['allowed_types'] = '*';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['overwrite'] = TRUE;
$config['file_name'] = date('U') . '_' . $_FILES['product_image']['name'];
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('product_image')) {
$error = array('error' => $this->upload->display_errors());
print_r($error);
die;
} else {
if ($this->upload->do_upload('product_image')) {
$image_data = $this->upload->data();
$full_path = $config['file_name'];
$data["product_pic"] = $full_path;
$query = $this->data_model->add_data($data, 'product');
if ($res == TRUE) {
echo "product added";
$data['items'] = $this->data_model->get_data_info('product_id', 'product');
$this->load->view('product', $data);
} else {
echo"product already exists";
$data['items'] = $this->data_model->get_data_info('product_id', 'category');
$this->load->view('product', $data);
}
}
}
}
$this->load->view('product');
}
model code
function add_data($data, $table) {
if ($query = $this->db->insert($table,$data)) {
$insert_id = $this->db->insert_id();
return $insert_id;
} else {
return false;
}
}

Unlink function has not been successful with codeigniter

I want to delete the image long after I update the new image. I have added unlink(), but the old image is not deleted.
Controller :
public function Update()
{
$id = $this->input->post('id');
$name = $this->input->post('name');
if($_FILES['image']['name']!="")
{
$config['upload_path'] = './image/';
$config['allowed_types'] ='gif|jpg|png|jpeg|jpe|pdf|doc|docx|rtf|text|txt';
$this->load->library('upload', $config);
if($this->upload->do_upload('image')){
$uploadData = $this->upload->data();
$image = $uploadData['file_name'];
}else{
$image= '';
}
}else{
$image = '';
}
$data = array(
'name' => $name,
);
if($image != ''){
$data['image'] = $image;
unlink("./image/$row->file_name");
}
$this->model_user->update_user($data,$id);
}
Model :
public function update_user($data, $id)
{
$this->db->where('id', $id);
return $this->db->update('table_user', $data);
}
In your code, you are not getting old image name from DB
First, get the old image name and then try like this
if($image != ''){
$data['image'] = $image;
$oldimage = $this->model_user->get_oldimage($id);
unlink("path/to/directory/".$oldimage);
}
Model
public function get_oldimage($id){
return $this->db->get_where('table_user', ['id' => $id])->row()->image;
}

Invalid argument supplied for foreach()

I do not understand how to fix this codes:
return $this->db->update('slideshow');
I have tried several codes like changing it to $query or $query_result etc. and the error still exist. I still have to use $this->db->update('');
controllers/Cuploadfile.php
function uploadedit()
{
$data['images'] = ''; // Need to place it here and get images here.
//set preferences
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'jpg|gif';
$config['max_size'] = '500000';
//load upload class library
$this->load->library('upload', $config);
$this->load->model('Mpages');
if (!$this->upload->do_upload('filename'))
{
// case - failure
$upload_error = array('error' => $this->upload->display_errors());
$this->load->view('addslideshows', $upload_error);
}
else
{
// case - success
$upload_data = $this->upload->data();
$filename = $upload_data['file_name'];
$image_id = $this->uri->segment(3);
$data['images'] = $this->Mpages->edit_slideshow($filename, $image_id);
$data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . $upload_data['file_name'] . '</strong> was successfully uploaded!</div>';
$this->load->view('editslideshows', $data);
}
}
models/Mpages.php
public function edit_slideshow($filename, $image_id)
{
$this->db->set('slideshow_image', $filename);
$this->db->where('image_id', $image_id);
return $this->db->update('slideshow');
}
Change your Model's function to this
public function edit_slideshow($filename, $image_id){
$this->db->where('image_id', $image_id);
$this->db->update('slideshow', $filename);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
rewrite your model
public function edit_slideshow($filename, $image_id)
{
$this->db->set('slideshow_image', $filename);
$this->db->where('image_id', $image_id);
$update=$this->db->update('slideshow');
if($update)
{
return true;
}
return false;
}

Stop form validation submitting if error on file upload

Question: When the user has filled in the form validation correct but there is a error on image upload how is it possible to stop the form being submitted
Currently still submits data even if there is a error on my image upload.
<?php
class Users extends MY_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('countries');
$this->load->library('upload');
$this->load->model('admin/user/user_model');
$this->load->model('admin/user_group/usergroup_model');
}
public function add() {
$this->form_validation->set_rules('username', 'Username', 'trim|required');
if ($this->form_validation->run() == true) {
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0) {
if (!is_dir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/')) {
mkdir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/');
}
$config['upload_path'] = './uploads/users/' . $this->input->post('username') . '/';
$config['allowed_types'] = 'gif|png';
$config['max_size'] = 3000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if ($this->upload->do_upload('userfile')) {
return true;
}
}
$this->user_model->insert($this->upload->data());
}
if ($this->upload->display_errors() != false) {
$this->error['warning'] = $this->upload->display_errors();
}
if (validation_errors() != false) {
$this->error['warning'] = validation_errors('<div class="alert alert-danger">', '</div>');
}
if (isset($this->error['warning'])) {
$data['warning_error'] = $this->error['warning'];
} else {
$data['warning_error'] = '';
}
$data['countries'] = $this->countries->get();
$data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
$data['usergroups'] = $this->usergroup_model->get_user_groups();
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('user/add_view', $data);
}
}
Model
<?php
class User_model extends CI_Model {
public function insert($upload_data = array()) {
$this->db->trans_begin();
$options = [
'cost' => 12,
];
$hash = password_hash($this->input->post('password'), PASSWORD_BCRYPT, $options);
$data = array(
'user_group_id' => $this->input->post('user_group_id'),
'username' => $this->input->post('username'),
'password' => $hash,
'firstname' => $this->input->post('firstname'),
'lastname' => $this->input->post('lastname'),
'email' => $this->input->post('email'),
'image' => ($upload_data['file_name']) ? $upload_data['file_name'] : '',
'country' => $this->input->post('country'),
'timezone' => $this->input->post('timezone'),
'status' => $this->input->post('status'),
'date_added' => date('Y-m-d')
);
$this->db->set($data);
$this->db->insert($this->db->dbprefix . 'user');
if ($this->db->trans_status() === FALSE) {
$this->db->trans_rollback();
} else {
$this->db->trans_commit();
}
}
}
Codeigniter Version 3.1.0 & XAMPP Windows 10
Have solved it now.
<?php
class Users extends MY_Controller {
private $error = array();
public function __construct() {
parent::__construct();
$this->load->library('form_validation');
$this->load->library('countries');
$this->load->library('upload');
$this->load->model('admin/user/user_model');
$this->load->model('admin/user_group/usergroup_model');
}
public function add() {
$this->form_validation->set_rules('username', 'username', 'trim|required|is_unique[user.username]');
$this->form_validation->set_message('is_unique', 'Opps looks like someone has all ready got that {field}');
if ($this->form_validation->run() == true) {
if (isset($_FILES['userfile']) && $_FILES['userfile']['size'] > 0) {
if ($this->upload() == true) {
$this->user_model->insert($this->upload->data());
}
} else {
$this->user_model->insert();
}
}
if (validation_errors() != '') {
$this->error['warning'] = validation_errors('<div class="alert alert-danger">', '</div>');
}
if (isset($this->error['warning'])) {
$data['warning_error'] = $this->error['warning'];
} else {
$data['warning_error'] = '';
}
$data['countries'] = $this->countries->get();
$data['timezones'] = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
$data['usergroups'] = $this->usergroup_model->get_user_groups();
$data['header'] = Modules::run('admin/common/header/index');
$data['footer'] = Modules::run('admin/common/footer/index');
$this->load->view('user/add_view', $data);
}
public function upload() {
if (!is_dir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/')) {
mkdir(FCPATH . 'uploads/users/' . $this->input->post('username') . '/');
}
$config['upload_path'] = './uploads/users/' . $this->input->post('username') . '/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 3000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile')) {
$this->error['warning'] = $this->upload->display_errors('<div class="alert alert-danger">', '</div>');
} else {
return true;
}
return !$this->error;
}
}

Codeigniter upload error

Please help me! I want to upload a file with codeigniter, but this return to error. This is the uploader:
class Uploader extends CI_Model
{
function __construct()
{
parent::__construct();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|exe|xls|doc|docx|xlsx|rar|zip';
$config['max_size'] = '8192'; // kbytes
$config['encrypt_name'] = TRUE;
$this->load->library( 'upload', $config );
$this->response = '';
$this->success = TRUE;
}
/**
* Triggers upload
* returns the file's details on success or false
*/
function upload( $field_name )
{
if ( !$this->upload->do_upload( $field_name ) )
{
$this->success = FALSE;
$this->response = $this->upload->display_errors();
return false;
}
else
{
$this->success = TRUE;
$this->response = $this->upload->data();
return $this->response['file_name'];
}
}
}
And this is the error message:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Downloads::$required_empty
Filename: core/Model.php
Line Number: 51
The autoload database config is on. Please help me.
try this
if($this->input->post())
{
$file_element_name = 'image'; //this is the name of your input file. for example "image"
if ($_FILES['image']['name']!= "")
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|exe|xls|doc|docx|xlsx|rar|zip';
$config['max_size'] = '8192';
$config['remove_spaces']=TRUE; //it will remove all spaces
$config['encrypt_name']=TRUE; //it wil encrypte the original file name
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('error',$error['error']);
redirect('controller_name/function_name','refresh');
}
else
{
$data = $this->upload->data();
return $data['file_name'];
}
$this->session->set_flashdata('msg','success message');
redirect('controller_name/function_name','refresh');
}
else
{
//if no file uploaded the do stuff here
}
}
please let me know if you face any problem.
have you tried something like this
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
you can get more here http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
The Upload Folder
You'll need a destination folder for your uploaded images. Create a
folder at the root of your CodeIgniter installation called uploads and
set its file permissions to 777.

Resources