Upload Query Codeigniter - codeigniter

I have done the below code and I now get a database error -> Still cannot seem to get it to upload:
Error:
Column 'image_path' cannot be null
Database Structure
Controller:
class Addsale extends CI_Controller {
function __construct(){
parent::__construct();
}
function index() {
if(!$this->session->userdata('logged_in')) {
redirect('admin/home');
}
// Main Page Data
$data['cms_pages'] = $this->navigation_model->getCMSPages();
$data['title'] = 'Add Sale';
$data['content'] = $this->load->view('admin/addsale', $data);
$this->load->view('admintemplate', $data);
//Set Validation
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('location', 'Location', 'trim|required');
$this->form_validation->set_rules('bedrooms', 'Bedrooms', 'trim|is_natural|required');
$this->form_validation->set_rules('bathrooms', 'Bathrooms', 'trim|required');
$this->form_validation->set_rules('condition', 'Condition', 'trim|required');
$this->form_validation->set_rules('description', 'Description', 'trim|required');
$this->form_validation->set_rules('price', 'Price', 'trim|required');
if($this->form_validation->run() === TRUE) {
$this->load->library('upload', $config);
$file_info = $this->upload->do_upload();
$data = array(
'name' => $this->input->post('name', TRUE),
'location' => $this->input->post('location', TRUE),
'bedrooms' => $this->input->post('bedrooms', TRUE),
'bathrooms' => $this->input->post('bathrooms', TRUE),
'condition' => $this->input->post('condition', TRUE),
'description' => $this->input->post('description', TRUE),
'price' => $this->input->post('price', TRUE),
'image_path' => $file_info['full_path']
);
$this->sales_model->addSale($data);
}
}
function do_upload(){
//Set File Settings
$config['upload_path'] = './includes/uploads/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
}
}
Model:
function addSale($data) {
$this->db->insert('sales', $data);
return;
}
Original Code:
Hello,
I have the following section of code:
if($this->form_validation->run() === TRUE) {
$data = array(
'name' => $this->input->post('name', TRUE),
'location' => $this->input->post('location', TRUE),
'bedrooms' => $this->input->post('bedrooms', TRUE),
'bathrooms' => $this->input->post('bathrooms', TRUE),
'condition' => $this->input->post('condition', TRUE),
'description' => $this->input->post('description', TRUE),
'price' => $this->input->post('price', TRUE),
'image_path' => $this->input->post('userfile', TRUE)
);
$this->load->library('upload', $config);
$this->upload->do_upload();
}
}
What I am trying to do is when the form is valid save the data to the database (works fine) and upload the image.
Were I am struggling is that I cannot get the userfile "name" to save and the file will not upload.
Can this be done within the index function?

Files that are uploaded don't get included in post at all, so you can't get the name in the way you want it. You'll have to do something like this instead:
if($this->form_validation->run() === TRUE) {
$this->load->library('upload', $config);
$file_info = $this->upload->do_upload();
$data = array(
'name' => $this->input->post('name', TRUE),
'location' => $this->input->post('location', TRUE),
'bedrooms' => $this->input->post('bedrooms', TRUE),
'bathrooms' => $this->input->post('bathrooms', TRUE),
'condition' => $this->input->post('condition', TRUE),
'description' => $this->input->post('description', TRUE),
'price' => $this->input->post('price', TRUE),
'image_path' => $file_info['full_path']
);
}
This will put the full path into your database if you just want the file name use 'client_name' or something (see Ross' answer for reference)

The function $this->upload->do_upload() returns an array of information about the file uploaded.
So:
$upload_data = $this->upload->do_upload();
print_r($upload_data); // to see everything
Array
(
[file_name] => mypic.jpg
[file_type] => image/jpeg
[file_path] => /path/to/your/upload/
[full_path] => /path/to/your/upload/jpg.jpg
[raw_name] => mypic
[orig_name] => mypic.jpg
[client_name] => mypic.jpg
[file_ext] => .jpg
[file_size] => 22.2
[is_image] => 1
[image_width] => 800
[image_height] => 600
[image_type] => jpeg
[image_size_str] => width="800" height="200"
)
So, depending on the value you need, you will want to do the upload first, and if it is successful, continue with processing the POST data. Then you can do this in your $data array:
'image_path' => $upload_data['file_name']; // adjust value to get what you want.
and you should be good to go.

Related

session userdata has null initials, is not inputted into the database

I have a code like this, the problem is when I input why the id_user value is "0".
even though the admin logged in is "1"
Is there anything missing in my script code?
Controller
public function tambah() {
// $this->session->set_userdata('upload_image_file_manager',true);
$kategori = $this->kategori_m->tampil();
$this->session->set_userdata('upload_image_file_manager',true);
// Validasi
$valid = $this->form_validation;
$valid->set_rules('judul_berita','Judul','required',
array( 'required' => 'Judul harus diisi'));
$valid->set_rules('isi_berita','Isi','required',
array( 'required' => 'Isi berita harus diisi'));
if($valid->run()) {
if(!empty($_FILES['gambar']['name'])) {
$config['upload_path'] = './resch/dev/admin/assets/media/';
$config['allowed_types'] = 'gif|jpg|png|svg|jpeg';
$config['max_size'] = '20480'; // 2 Mb
$this->load->library('upload', $config);
if(! $this->upload->do_upload('gambar')) {
// End validasi
$data = array( 'head_title' => 'Berita- Edutech Solution',
'title' => 'Tambah Berita',
'head_menu' => 'Berita',
'sub_title' => 'Total Berita',
'kategori' => $kategori,
'error' => $this->upload->display_errors(),
'isi' => 'superadmin/berita/tambah');
$this->load->view('superadmin/template/wrapper_admin', $data, FALSE);
// Masuk database
}else{
$upload_data = array('uploads' =>$this->upload->data());
// Image Editor
$config['image_library'] = 'gd2';
$config['source_image'] = './resch/dev/admin/assets/media/'.$upload_data['uploads']['file_name'];
$config['new_image'] = './resch/dev/admin/assets/media/thumbs';
$config['create_thumb'] = TRUE;
$config['quality'] = "100%";
$config['maintain_ratio'] = TRUE;
$config['width'] = 360; // Pixel
$config['height'] = 360; // Pixel
$config['x_axis'] = 0;
$config['y_axis'] = 0;
$config['thumb_marker'] = '';
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$i = $this->input;
$slug = url_title($i->post('judul_berita'),'dash',TRUE);
$data = array( 'id_kategori' => $i->post('id_kategori'),
'id_user' => $this->session->userdata('user_name'),
'slug_berita' => $slug,
'judul_berita' => $i->post('judul_berita'),
'isi_berita' => $i->post('isi_berita'),
'jenis_berita' => $i->post('jenis_berita'),
'status_berita' => $i->post('status_berita'),
'gambar' => $upload_data['uploads']['file_name'],
// 'icon' => $i->post('icon'),
'keyword' => $i->post('keyword'),
'tanggal_publish'=> date('Y-m-d',strtotime($i->post('tanggal_publish'))).' '.$i->post('jam_publish'),
// 'tanggal_mulai' => $i->post('tanggal_mulai'),
// 'tanggal_selesai' => $i->post('tanggal_selesai'),
// 'urutan' => $i->post('urutan'),
'tanggal_post' => date('Y-m-d H:i:s'),
);
$this->berita_m->tambah($data);
$this->session->set_flashdata('sukses', 'Data telah ditambah');
redirect(base_url('superadmin/berita/jenis_berita/'.$i->post('jenis_berita')),'refresh');
}}else{
$i = $this->input;
$slug = url_title($i->post('judul_berita'),'dash',TRUE);
$data = array( 'id_kategori' => $i->post('id_kategori'),
'id_user' => $this->session->userdata('user_name'),
'slug_berita' => $slug,
'judul_berita' => $i->post('judul_berita'),
'isi_berita' => $i->post('isi_berita'),
'jenis_berita' => $i->post('jenis_berita'),
'status_berita' => $i->post('status_berita'),
'gambar' => $upload_data['uploads']['file_name'],
// 'icon' => $i->post('icon'),
'keyword' => $i->post('keyword'),
'tanggal_publish'=> date('Y-m-d',strtotime($i->post('tanggal_publish'))).' '.$i->post('jam_publish'),
// 'tanggal_mulai' => $i->post('tanggal_mulai'),
// 'tanggal_selesai' => $i->post('tanggal_selesai'),
// 'urutan' => $i->post('urutan'),
'tanggal_post' => date('Y-m-d H:i:s'),
);
$this->berita_m->tambah($data);
$this->session->set_flashdata('sukses', 'Data telah ditambah');
redirect(base_url('superadmin/berita/jenis_berita/'.$i->post('jenis_berita')),'refresh');
}}
// End masuk database
$data = array( 'head_title' => 'Berita- Edutech Solution',
'title' => 'Tambah Berita',
'head_menu' => 'Berita',
'sub_title' => 'Total Berita',
'kategori' => $kategori,
'isi' => 'superadmin/berita/tambah');
$this->load->view('superadmin/template/wrapper_admin', $data, FALSE);
}
in a model like this, I feel there is no problem
Model
public function tampil() {
$this->db->select('berita.*, user.nama, kategori.nama_kategori, kategori.slug_kategori');
$this->db->from('berita');
// Join dg 2 tabel
$this->db->join('kategori','kategori.id_kategori = berita.id_kategori','LEFT');
$this->db->join('user','user.id_user = berita.id_user','LEFT');
// End join
$this->db->order_by('id_berita','DESC');
$query = $this->db->get();
return $query->result();
}
// Tambah
public function tambah($data) {
$this->db->insert('berita',$data);
}
session userdata has null initials, not inputted to the database and
because I was confused, I skip. and create a function to update, but when the update function is executed it will give an error "too few arguments to functio"
I don't understand the problem.

Form input not cleared after ajax submission

I have a form with one field and a submit button with ajax submission option like following -
public function buildForm(array $form, FormStateInterface $form_state, $id = 0)
{
$form['fieldset']['message'] = array(
'#type' => 'textfield',
'#default_value' => "",
'#required' => true,
'#attributes' => array(
'placeholder' => t('write here'),
),
);
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Send'),
'#attributes' => array(
'class' => array(
),
),
'#ajax' => [
'callback' => [$this, 'Ajaxsubmit'],
'event' => 'click']
);
return $form;
}
The ajax function is following -
public function Ajaxsubmit(array $form, FormStateInterface $form_state)
{
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$db_values = [
"message" => $form_state->getValue("message"),
"date_create" => date("Y-m-d H:i:s"),
];
$save = DbStorage::Insert($db_values);
//$('#mychat_form input').val("");
//$form_state->setValue('content', NULL);
$response = new AjaxResponse();
if ($form_state->hasAnyErrors() || !$save) {
$response->addCommand(new AlertCommand('something wrong!'));
} else {
$message = DbStorage::Get(["id" => $save]);
$send_id = $message->send_id;
$build = [
'#theme' => "chat_view",
'#message' => $message,
'#sender' => $send_id,
'#current_user' => true
];
$ans_text = render($build);
$response->addCommand(new AppendCommand('#mychat', $ans_text));
}
return $response;
}
Here form data submission is working fine. But input data is not cleared after submission. I tried to clear it from my javascript using -
$('#my_form input').val("");
But the problem is my javascript file is called every 3 seconds and the form input is also cleared in every 3 seconds. this is problematic for users. Is there any other way to clear the form input after the ajax submission ? Can i do anything inside Ajaxsubmit function ?
You can use InvokeCommand for doing it.
For e.g: to clear an input value $('#my_form input').val(""); in ajax response
use Drupal\Core\Ajax\HtmlCommand;
use Drupal\Core\Ajax\InvokeCommand;
use Drupal\Core\Ajax\AppendCommand;
:
$form['fieldset']['message'] = array(
'#type' => 'textfield',
'#default_value' => "",
'#required' => true,
'#attributes' => array(
'placeholder' => t('write here'),
'class' => ['custom-class'],
),
);
In Ajax function
:
$build = [
'#theme' => "chat_view",
'#message' => $message,
'#sender' => $send_id,
'#current_user' => true
];
$response->addCommand(new AppendCommand('#mychat', $build));
$response->addCommand(new InvokeCommand('.custom-class', 'val', ['']));

ZF2 simple form validation

I tried to validate a simple form in zend framework 2 for days now.
I checked the documentation and a lot of posts considering this topic but I found no solution!
I have a very simple form:
class AlimentForm extends Form
{
public function __construct($name = null)
{
parent::__construct('aliment');
$this->add(array(
'required'=>true,
'name' => 'year',
'type' => 'Text',
'options' => array(
'label' => 'Jahr',
),
));
$this->add(array(
'required'=>true,
'name' => 'number',
'type' => 'Text',
'options' => array(
'label' => 'Number',
),
));
$this->add(array(
'name' => 'submit',
'type' => 'Submit',
'attributes' => array(
'value' => 'Go',
'id' => 'submitbutton',
),
));
}
}
I created a custom InputFilter:
namespace Application\Form;
use Zend\InputFilter\InputFilter;
class AlimentInputFilter extends InputFilter {
public function init()
{
$this->add([
'name' => AlimentForm::year,
'required' => true,
'validators' => array(
array(
'name' => 'Between',
'options' => array(
'min' => 1900,
'max' => 3000,
),
),
),
]);
}
}
and finally in my controller I try to validate the form
public function alimentAction(){
$form = new AlimentForm();
$form->setInputFilter(new AlimentInputFilter());
$request = $this->getRequest();
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
$year = $form->get('year')->getValue();
$number = $form->get('number')->getValue();
return array('result' => array(
"msg" => "In the Year ".$year." you get ".$number." Points"
));
}
}
return array('form' => $form);
}
It can't be that difficult, but from all those different ways to validate a form I found in the net, I'm a bit confused...
What am I missing?
Greetings and thanks in advance
U.H.
Ok, I solved the problem.
I created a Model for the aliment Form that has a year and a number attribute
and I defined an input filter within that model:
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Aliment implements InputFilterAwareInterface
{
public $year;
public $number;
public function exchangeArray($data){
$this->year = (!empty($data['year']))?$data['year']:null;
$this->number = (!empty($data['number']))?$data['number']:null;
}
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();
$inputFilter->add(array(
'name' => 'year',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Between',
'options' => array(
'min' => 1900,
'max' => 3000
)
)
),
));
$inputFilter->add(array(
'name' => 'number',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'Between',
'options' => array(
'min' => 1,
'max' => 10
)
)
),
));
$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}
}
In the action method of the controller I was able to set the InputFilter of the model to the form and voila! It worked!
public function alimentAction(){
$form = new AlimentForm();
$request = $this->getRequest();
if ($request->isPost()) {
$aliment = new \Application\Model\Aliment;
$form->setInputFilter($aliment->getInputFilter());
$form->setData($request->getPost());
if ($form->isValid()) {
$aliment->exchangeArray($form->getData());
$year = $form->get('year')->getValue();
return array(
'result' => array(
//your result
)
);
}
}
return array('form' => $form);
}
The form is correctly validated now and returns the corresponding error messages.
I hope, it help somebody whos got similar problems with validating!

file_get_contents() expects parameter 1 to be a valid path

My image is uploading to images/news successfully. I want to now save that image in the database. but it keeps giving me the above error. My model query is correct because i use it to insert other data and it works.
How can i save the image into the database once the user clicks submit?
My controller:
function news()
{
$config = array(
'upload_path' => "./images/news",
'allowed_types' => "gif|jpg|png|jpeg|JPG",
'overwrite' =>False,
'max_size' => "2048000",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
$this->load->helper(array('form', 'url'));
if($this->upload->do_upload())
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('manage_news',$data);
}
else
{
$message2 = "Please choose another file type. gif,jpg,png,jpeg,pdf ";
echo "<script type='text/javascript'>alert('$message2'); </script>";
redirect('resetPasswordController/add_news', 'refresh');
}
$this->db->trans_start();
$data = array('upload_data' => $this->upload->data());
$data = array(
'image' => file_get_contents( $data )
);
$this->load->model('users_model');
$this->users_model->insert($data);
$this->db->trans_complete();
$this->db->trans_complete();
redirect('resetPasswordController/manage_news', 'refresh');
}
my view:
<?php echo form_open_multipart('resetPasswordController/news');?>
<label>Image</label>
<input name = "userfile" type="file" />
my model:
function insert($data){
$this->db->insert('news',$data);
return $this->db->insert_id();
}
$data contain array values, you have to use upload_data
for ex :
$data = array('upload_data' => $this->upload->data());
$data = array(
'image' => file_get_contents( $data )
);
change this to
$data = array('upload_data' => $this->upload->data());
$data = array(
'image' => file_get_contents( $data['upload_data'] )
);
or
you can directly use upload data function
$data = array(
'image' => file_get_contents( $this->upload->data())
);

Multiple thumbnails at once in CodeIgniter

At the moment at once I'm learning and trying, to what CodeIgniter is able to. But I stuck at multiple thumbnails making at once. Probably, I messed up my head too much using Wordpress, and trying to do something like this in Codeigniter, but anyways, here is my code
<?php
class Gallery_model extends CI_Model {
var $gallery_path;
function __construct() {
parent::__construct();
$this->load->helper('functions');
$this->gallery_path = realpath(APPPATH . '../uploads');
}
function do_upload() {
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png',
'upload_path' => $this->gallery_path,
'max_size' => 2000
);
$this->load->library('upload', $config);
$this->upload->do_upload();
$image_data = $this->upload->data();
$image_sizes = array(
'thumb' => array(150, 100),
'medium' => array(300, 300),
'large' => array(800, 600)
);
foreach ($image_sizes as $resize) {
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->gallery_path . '-' . $resize[0] . 'x' . $resize[1],
'maintain_ration' => true,
'width' => $resize[0],
'height' => $resize[1]
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
}
}
At the moment, I'm able to create just an image it self, but I cant make thumbnails with this. Maybe someone could enhance the code, and get it work :)
PS - I tried just take everything after $image_sizes, put it in other independent php file, run it, and var dump the $config inside of foreach, and it seemed like working.
Use it like this:
$this->load->library('image_lib');
foreach ($image_sizes as $resize) {
$config = array(
'source_image' => $image_data['full_path'],
'new_image' => $this->gallery_path . '-' . $resize[0] . 'x' . $resize[1],
'maintain_ration' => true,
'width' => $resize[0],
'height' => $resize[1]
);
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
}
initialize works better than loading the library with the $config.
I Solved It.
I Create this function to create Multiple Thumbnails:
function _create_thumbs($file_name){
// Image resizing config
$config = array(
// Large Image
array(
'image_library' => 'GD2',
'source_image' => './assets/images/'.$file_name,
'maintain_ratio'=> FALSE,
'width' => 700,
'height' => 467,
'new_image' => './assets/images/large/'.$file_name
),
// Medium Image
array(
'image_library' => 'GD2',
'source_image' => './assets/images/'.$file_name,
'maintain_ratio'=> FALSE,
'width' => 600,
'height' => 400,
'new_image' => './assets/images/medium/'.$file_name
),
// Small Image
array(
'image_library' => 'GD2',
'source_image' => './assets/images/'.$file_name,
'maintain_ratio'=> FALSE,
'width' => 100,
'height' => 67,
'new_image' => './assets/images/small/'.$file_name
));
$this->load->library('image_lib', $config[0]);
foreach ($config as $item){
$this->image_lib->initialize($item);
if(!$this->image_lib->resize()){
return false;
}
$this->image_lib->clear();
}
}
And then, I call that function when I upload the image like this:
function do_upload(){
$config['upload_path'] = './assets/images/'; //path folder
$config['allowed_types'] = 'gif|jpg|png|jpeg|bmp';
$config['encrypt_name'] = TRUE;
$this->upload->initialize($config);
if(!empty($_FILES['filefoto']['name'])){
if ($this->upload->do_upload('filefoto')){
$img = $this->upload->data();
//Compress Image
$this->_create_thumbs($img['file_name']);
$title = $this->input->post('title',TRUE);
$image_large = $img['file_name'];
$image_medium = $img['file_name'];
$image_small = $img['file_name'];
$this->upload_model->insert_images($title,$image_large,$image_medium,$image_small);
}else{
echo $this->upload->display_errors();
}
}else{
echo "image is empty or type of image not allowed";
}
}

Resources