Error in adding new item to my database using codeigniter - php

I have been getting this error while submiting a form using codeigniter. I need help even though I have been following the documentation.
I am using 2.x version of codeigniter
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Products::$input‐
Filename: core/Model.php
Line Number: 52
Fatal error: Call to undefined function post() in /opt/lampp/htdocs/gamingplace/application/models/product_model.php on line 63
This is the code in my model
//add new product
public function addProduct(){
$data = array(
'category_id' => $this->input‐>post('category_id'),
'title' => $this->input‐>post('title'),
'description' => $this->input‐>post('description'),
'price' => $this->input‐>post('price')
);
if($_FILES['image']['error'] == 0){
$data['image'] = $this->upload->file_name;
return $this->db->insert('products',$data);
}
}
}
This is the code in my controller
public function addProduct()
{
if($_FILES['image']['error'] == 0){
//setting image preferences
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'jpg|png|jpeg|PNG|JPEG|JPG';
$config['overwrite'] = false;
$config['quality'] = '100%';
$config['remove_spaces'] = true;
$config['max_size'] = '90';// in KB
$this->load->library('upload',$config);
echo $this->input->post('image');
if( ! $this->upload->do_upload('image'))
{
$this->session->set_flashdata('message_failed', $this->upload->display_errors('', ''));
redirect('dashboard');
}else{
//Image Resizing
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['maintain_ratio'] = FALSE;
$config['width'] = 311;
$config['height'] = 162;
$this->load->library('image_lib',$config);
if ( ! $this->image_lib->resize()){
$this->session->set_flashdata('message_failed', $this->image_lib->display_errors('', ''));
}
//calling a model an its method to add a new product to the database
if($this->product_model->addProduct()){
$upload_data = $this->upload->data();
$this->session->set_flashdata('message', 'A new product,'. $upload_data['file_name'].'has been added!');
redirect('dashboard');
}
}
}
}
}
And my view
<!-- Modal -->
<script src="<?php echo base_url(); ?>assets/js/validation.js" charset="utf-8"></script>
<div class="modal fade" id="addProduct" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Product</h4> <em>if the product category is not in the select option,
go to add category link to add category before adding this product</em>
</div>
<div class="modal-body">
<?php echo validation_errors('<div class="alert alert-danger">','</div>') ?>
<form role= "form" action="<?php echo base_url()?>products/addProduct" method="post" name="form" onsubmit="return validate(this)" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="title" class="form-control" placeholder="Enter name of product" required>
</div>
<div class="form-group">
<label>Brief Description of Product</label>
<textarea name="description" rows="8" cols="80" class="form-control">
This is a brand made by Gucci Company. Made of cotton, bla bla bla
</textarea>
</div>
<label>Select Category</label>
<div class="form-group">
<select class="form-control" name="category_id">
<?php foreach (get_categories_h() as $popular): ?>
<option value="<?php echo$popular->id?>"><?php echo $popular->name ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Enter or choose price</label>
<input type="number" id="price" class="form-control" name="price_old" required>
</div>
<input type="hidden" name="price" class="form-control" id="mainPrice"required>
<div class="form-group">
<input type="file" name="image" id="image" class="form-control" required accept="image/*" onChange="validateImage(this.value)">
</div>
<button type="submit" name="submit" class=" form-control btn btn-success">Add</button>
</form>
</form>
</div>
</div>
</div>
</div>

I think you may have a few issues going on with your code, but let's first focus on your question/error you mentioned. In your controller function, you are not passing the post to the model. You need to do something like this in the controller:
$addProduct = $this->product_model->addProduct($_POST);
if($addProduct){
$upload_data = $this->upload->data();
$this->session->set_flashdata('message', 'A new product,'. $upload_data['file_name'].'has been added!');
redirect('dashboard');
}
In the model function, you need to first let the function know there is an incoming parameter, then adjust how you are assigning the fields to the data array.
public function addProduct($post){
$data = array(
'category_id' => $post["category_id"],
'title' => $post["title"],
'description' => $post["description"],
'price' => $post["price"]
);
return $this->db->insert('products',$data);
}
After that, I noticed that you have some other FILES logic in your model. That will likely error out, too. I believe that is going to have to be done in the controller, not the model. Once you do the upload in the controller, you can pass the file name into the model as well.
$upload_data = $this->upload->data();
$addProduct = $this->product_model->addProduct($_POST, $upload_data['file_name']);
if($addProduct){
$this->session->set_flashdata('message', 'A new product,'. $upload_data['file_name'].'has been added!');
redirect('dashboard');
}
Then, adjust the model.
public function addProduct($post, $fileName){
$data = array(
'category_id' => $post["category_id"],
'title' => $post["title"],
'description' => $post["description"],
'price' => $post["price"],
'image' => $fileName
);
return $this->db->insert('products',$data);
}
Hope this helps.

Related

Laravel 8, how to upload more than one image at a time

I want to upload more than one image at a time through an in Laravel 8 to my SQL database, and I am not able to do it. I have managed to upload only one, but when I try with more I get failure.
My Database
Imagenes
id
nombre
id_coche
01
name.jpg
0004
...
...
...
My Code
Blade with the Form
#foreach ($Vehiculo as $obj) /*this is to take the Car ID*/
<form method="POST" action="{{ route('añadirImagen')}}" enctype="multipart/form-data" >
#csrf
<div class="form-row">
<div class="form-group col-md-3">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">ID</span>
</div>
<input type="text" class="form-control" name="id_coche" value="{{$obj->id}}" style="background: white" required readonly>
</div>
</div>
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" required multiple/>
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-success">AÑADIR IMAGENES</button>
</div>
</div>
</form>
#endforeach
Controller
"To upload only one image"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'nombre.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->file("imagen")!=null){
$nombre = $request->file('imagen');
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
$Imagenes->save();
return redirect()->back()->with('error','Se han añadido las imagenes correctamente.');
}
}
"My attempt to upload more than one"
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'imagen.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->hasfile("imagen")){
$nombre_img = $request->file('imagen');
foreach($nombre_img as $nombre) {
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
}
$Imagenes->save();
When doing this, it adds in the database a single row, with the correct id_coche, the Auto_Increment does well the ID, but the name remains NULL.
Thank You.
You currently have:
<input type="file" class="form-control" name="imagen" required multiple/>
and it needs to be:
<input type="file" class="form-control" name="imagen[]" required/>
multiple attribute is not required.
Then you can do in your controller:
if($request->hasfile('imagen')) {
foreach($request->file('imagen') as $file)
{
...
}
}

i have error An uncaught Exception was encountered Type: ArgumentCountError Message: Too few arguments to function

I am making a news editing feature using CodeIgniter 3, there is also an image edit here
But has errors like the following,
An uncaught Exception was encountered
Type: ArgumentCountError
Message: Too few arguments to function Operator::edit_berita(), 0 passed in D:\xampp\htdocs\ui-desa\system\core\CodeIgniter.php on line 532 and exactly 1 expected
Filename: D:\xampp\htdocs\ui-desa\application\controllers\Operator.php
Line Number: 164
Backtrace:
File: D:\xampp\htdocs\ui-desa\index.php
Line: 315
Function: require_once
Controller Operator.php
public function edit_berita($id_berita)
{
$data['title'] = 'Edit Berita';
$data['user'] = $this->db->get_where(
'user',
['id' => $this->session->userdata('id')],
['email' => $this->session->userdata('email')]
)->row_array();
$data['berita'] = $this->model_berita->getAllBeritaById($id_berita);
// $data['berita'] = $this->db->get('berita')->result_array();
// $data['berita'] = $this->model_berita->getNama();
$this->form_validation->set_rules('judul_berita', 'Judul Berita', 'required');
$this->form_validation->set_rules('isi_berita', 'Isi Berita', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('templates/header', $data);
$this->load->view('templates/sidebar', $data);
$this->load->view('templates/topbar', $data);
$this->load->view('operator/editberita', $data);
$this->load->view('templates/footer');
} else {
$judul_berita = $this->input->post('judul_berita');
$slug_berita = url_title($this->input->post('judul_berita'), 'dash', 'TRUE');
$isi_berita = $this->input->post('isi_berita');
$tgl_berita = date('Y-m-d H:i:s');
$id = $this->session->userdata('id');
// Cek Jika Ada Gambar Yang DiUpload
$upload_image = $_FILES['gambar_berita'];
if ($upload_image) {
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['upload_path'] = './gambar_berita/';
$this->load->library('upload', $config);
if ($this->upload->do_upload('gambar_berita')) {
$old_image = $data['berita']['gambar_berita'];
if ($old_image != 'default.jpg') {
unlink(FCPATH . 'gambar_berita/' . $old_image);
}
$new_image = $this->upload->data('file_name');
$this->db->set('gambar_berita', $new_image);
} else {
echo $this->upload->display_errors();
}
}
$this->db->set('id_berita', $id_berita);
$data = array(
'judul_berita' => $judul_berita,
'isi_berita' => $isi_berita
);
$this->db->where($data);
$this->db->update('berita');
$this->session->set_flashdata('message', '<div class="alert alert-success" role ="alert"> Berita Berhasil di Reposting </div>');
redirect('operator/berita');
}
}
Model model_berita.php
public function getAllBeritaById($id_berita)
{
return $this->db->get_where('berita', ['id_berita' => $id_berita])->row_array();
}
View edit_berita.php
<!-- CK Editor 4 -->
<script src="<?= base_url('ckeditor/'); ?>ckeditor.js"></script>
<script src="<?= base_url('ckeditor/'); ?>samples/js/sample.js"></script>
<link href="<?= base_url('ckeditor/'); ?>samples/css/samples.css" rel="stylesheet">
<link href="<?= base_url('ckeditor/'); ?>samples/toolbarconfigurator/lib/codemirror/neo.css" rel="stylesheet">
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">
<?= $title; ?></h1>
<div class="row">
<div class="col-lg">
<?php if (validation_errors()) : ?>
<div class="alert alert-danger" role="alert">
<?= validation_errors(); ?>
</div>
<?php endif; ?>
<?= $this->session->flashdata('message'); ?>
<?= form_open_multipart('operator/edit_berita') ?>
<form action="" method="post">
<input type="hidden" name="id" value="<?= $berita['id_berita']; ?>">
<div class="modal-body">
<div class="form-group">
<small>Masukkan Judul Berita</small>
<input type="text" value="<?= $berita['judul_berita']; ?>" class="form-control" id="judul_berita" name="judul_berita" placeholder="Judul Berita..." required>
</div>
<div class="form-group">
<small>Masukkan Isi Berita</small>
<textarea class="form-control" name="isi_berita" id="editor" required><?= $berita['isi_berita']; ?></textarea>
</div>
<div class="form-group">
<label for="gambar_berita">Ganti Gambar Berita</label>
<div class="col-sm-12">
<div class="row">
<div class="col-sm-3">
<img src="<?= base_url('gambar_berita/') . $berita['gambar_berita']; ?>" class="img-thumbnail" alt="Gambar Berita">
</div>
<div class="col-sm-9">
<div class="custom-file">
<input type="file" class="custom-file-input" id="gambar_berita" name="gambar_berita">
<label class="custom-file-label" for="gambar_berita">Choose File</label>
</div>
</div>
</div>
</div>
<br>
<button type="reset" class="btn btn-danger" data-dismiss="modal">Reset</button>
<button type="submit" class="btn btn-primary">Add</button>
</div>
</form>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
<script>
initSample();
</script>
I've tried a number of ways, but it's still an error too. Please help so that my news update feature can work. Thanks.
Well your error clearly states that your method.
public function edit_berita($id_berita)
is expecting a parameter, which you have named $id_berita.
I cannot tell why you decided to have a parameter in this method, so I can only make some suggestions to help you solve your issue.
From what I can gather from your supplied code you could try the following options...
Option 1:
From what I can tell from your form, you are posting this as a hidden input, so you should be retrieving it from the Post Data.
<input type="hidden" name="id" value="<?= $berita['id_berita']; ?>">
So your method should become...
public function edit_berita()
{
$id_berita = $this->input->post('id'); // This needs to be validated
// The rest of your code below here...
}
But I would be validating that value to see if it exists before processing anything else.
Personally, I would be naming it as id_berita in your form to keep things matched up to avoid mistakes.
Option 2:
Another option would be to modify your form_open_mulitpart from
<?= form_open_multipart('operator/edit_berita') ?>
To include the id to pass in as a parameter
<?= form_open_multipart('operator/edit_berita/'.$berita['id_berita']) ?>
You will have to check that by inspecting your HTML Source using your Browsers "View Source" and inspect the HTML to see that it has ended up in the right place.
That will let you use your existing method
public function edit_berita($id_berita)
But again, you would need to validate that the passed in $id_berita is correct.
Which ever way you go, is your choice. You just need to read through your code and understand it a bit better.
I hope that gives you some guidance.

decode and move base64 encoded image in laravel

I am trying to implement a image upload with other form elements with dropzone.js in laravel. So far I've managed to display the drag and drop image upload view with other form elements. And also get POST details from the submitted form. But when dropzone is passing the uploaded image to the database data save function it encode image with base64. I think I've managed to get the file extension also. And when I submit the button it gives me this error "Call to a member function move() on string" . Please put me in the right direction.
Here is the Form
<form class="form-horizontal" action="{{ route('save-slider-content') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sliderTitle" id="sliderTitle" placeholder="Title of the post goes here">
</div>
</div>
<input type="hidden" name="date" id="date" value="<?php echo date("d-m-Y"); ?>">
<div class="form-group">
<label for="image" class="col-sm-2 control-label">Image</label>
<input hidden id="file" name="file"/>
<div class="col-sm-10">
<div class="dropzone needsclick dz-clickable" id="fileUpload">
<div class="dz-default dz-message">
<i class="fa fa-image fa-5x"></i>
<h3 class="sbold">Drop an image here to upload</h3>
<span>You can also click to open file browser</span>
</div>
</div>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Link</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sliderLink" id="sliderLink" placeholder="Provide a link">
</div>
</div>
</div><br>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-info pull-right">Post</button>
</div>
<!-- /.box-footer -->
</form>
Here is the dropzone configuration
<script type="text/javascript">
Dropzone.options.fileUpload = {
url: "save-slider-content",
addRemoveLinks: true,
accept: function(file) {
let fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onloadend = function() {
let content = fileReader.result;
$('#file').val(content);
file.previewElement.classList.add("dz-success");
}
file.previewElement.classList.add("dz-complete");
}
}
</script>
Route
Route::post('store-slider-content', [ 'as' => 'save-slider-content', 'uses' => 'SliderContent#save_slider_data']);
save_slider_data function in Controller
public function save_slider_data(Request $request)
{
$slider = new Slider;
$slider->title = $request->sliderTitle;
$slider->title_sin = $request->sliderTitleSin;
$slider->date = $request->date;
$slider->link = $request->sliderLink;
$file = $request->file;;
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
$f = finfo_open();
$mime_type = finfo_buffer($f, $image_data, FILEINFO_MIME_TYPE);
$imageName = time().'.'.$mime_type;
$image_data->move(public_path('slider_uploads'), $imageName);
return response()->json(['success'=>$imageName]);
$slider->img_url = $imageName;
$slider->save();
}
Edited to include the logic for either Symfony\Component\HttpFoundation\File\File or Illuminate\Support\Facades\File (Illuminate\Filesystem\Filesystem)
move is a method of a File object, but $image_data is just a string. So one thing you could do is write the decoded image to a temp file, instantiate a File of it, and move it, like
//... your code ...
$image_data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $file));
// ... and then:
//grab a new tmp file
$tmpFilePath=sys_get_temp_dir().'/'.uniqid();
//write the image to it
file_put_contents($tmpFilePath, $image_data);
//move it.
//give it a name
$imageName = time().'.'.str_replace("image/","",$mime_type);
//if using Symfony\Component\HttpFoundation\File\File;
//get an instance of File from the temp file and call ->move on it
$tmpFile=new File($tmpFilePath);
$tmpFile->move(public_path('slider_uploads'), $imageName);
//or if using File facade
File::move($tmpFilePath, public_path("slider_uploads/$imageName"));
//...and then, back to your code...
$slider->img_url = $imageName;
$slider->save();
return response()->json(['success'=>$imageName]);
}
You can do this:
In config/filesystems.php, register a new disk slider_uploads
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
],
'slider_uploads' => [
'driver' => 'local',
'root' => public_path('slider_uploads')
]
]
And then use your new disk in storing your image
$image_data = $request->file;
#list($type, $image_data ) = explode(';', $image_data );
#list(, $image_data ) = explode(',', $image_data );
if($image_data !=""){ // storing image in public/slider_uploads/ Folder
\Storage::disk('slider_uploads')->put($imageName, base64_decode($image_data ));
}

codeigniter form not submitting data

I have tried everything I can think of but whenever I click submit the form passes on a null value, I dont know if it is the problem with the form or the controller or even the view. I changed this->input->post to posted data and i get an error of undefined variable posted data, please help.
Controller:
public function addmenu(){
$this->load->model('organizer_model');
$data = array(
'menu_name' => $this->input->post('menu name'),
'price' => $this->input->post('price'),
'email' => $this->session->userdata('email')
);
if($this->organizer_model->insertmenu($data)) {
$this->session->set_flashdata('message', 'Your menu has been added');
redirect('/menu/index', 'refresh');
} else {
$this->session->set_flashdata('message', 'Your menu was not added, please try again');
redirect('/menu/index', 'refresh');
}
View:
<form action="<?php echo site_url('Organizer/addmenu'); ?>" method="post" class="form-horizontal no-margin">
<div class="control-group">
<label class="control-label" for="menuname">
Menu Name
</label>
<div class="controls controls-row">
<input class="span3" name="data[menuname]" type="text" placeholder="Enter menu Name">
</div>
</div>
<div class="control-group">
<label class="control-label" for="price">
Price
</label>
<div class="controls controls-row">
<input class="span3" name="data[price]" type="text" placeholder="">
</div>
</div>
<div class="form-actions no-margin">
<button type="submit" name="submit" class="btn btn-info pull-right">
Add menu
</button>
<div class="clearfix">
</div>
</div>
</form>
Model:
public function insertmenu($data) {
$condition = "email = '" . $data['email'] . "'";
$this->db->select('organizer_id');
$this->db->from('organizer');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() > 0){
array_pop($data); //will remove email from data
$row = $query->row();
$data['organizer_id'] = $row->organizer_id;
$this->db->insert('menu', $data);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
} else {
return false;
}
}
I notice same question here codeigniter- insert data into db not working
Checks
Make sure you load your form helper and url helper.
Make sure you use form validation when submitting form in codeigniter on controller.
From this php user guide here http://php.net/manual/en/reserved.variables.post.php
Example on your input would be like person[0][first_name]
<form action="" method="">
<input type="text" name="data_posts[0][menu_name]" placeholder="Enter menu Name">
<input type="text" name="data_posts[0][price]" placeholder="">
</form>
Model
<?php
class Model_something extends CI_Model {
public function add_menu() {
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$data = array(
'email' => $this->session->userdata('email'),
'menu_name' => $data_post['menu_name'],
'price' => $data_post['price']
);
$this->db->insert('tablename', $data);
}
}
}
Controller
<?php
class Add_menu extends CI_Controller {
public function index() {
$this->load->helper('form');
$this->load->helper('url');
$this->load->library('form_validation');
$data_posts = $this->input->post('data_posts');
foreach ($data_posts as $data_post) {
$this->form_validation->set_rules('data_posts['.$data_post.'][menu_name]', 'Menu Name', 'required');
$this->form_validation->set_rules('data_posts['.$data_post.'][price]', 'Price', 'required');
}
if ($this->form_validation->run() == FALSE) {
$this->load->view('some_view');
} else {
$this->load->model('model_something');
$this->model_something->add_menu();
redirect('to_success_page');
}
}
}
You could also check if has been inserted by using callback function
Codeigniter 3 user guide form validation http://www.codeigniter.com/user_guide/libraries/form_validation.html
Codeigniter 2 user guide form validation http://www.codeigniter.com/userguide2/libraries/form_validation.html
Also you should upgrade to the new bootstrap I see your using old version.

Uploading file with php

I have the following set up in a Code Igniter application, however the file is not being passed through to the file uploader class. This is the second form on the page, just for reference and I have checked that they are both closed correctly.
The output I am getting is You did not select a file to upload. when I have been selecting an valid image.
View
<form action="../albums/upload" class="form-horizontal" method="post">
<div class="form-group">
<input type="file" name="userfile" required="" class="form-control">
</div>
<div class="form-group">
<div class="col-md-4 col-md-offset-4">
<input type="submit" id="upload" name="upload" class="btn btn-success" value="Upload">
</div>
</div>
</form>
Controller
public function upload() {
if($this->input->post('userfile')){
$this->model_photo->do_upload();
}
}
Model
function do_upload() {
$path = base_url().'res/image/';
$config = array(
'allowed_types' => 'jpg|jpeg|gif|png|tif|tiff',
'upload_path' => $path
);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
echo $error['error']; //echo debugging purposes
} else {
$data = array('upload_data' => $this->upload->data());
echo $data['upload_data']; //echo debugging purposes
}
}
in your <form> add enctype="multipart/form-data"
<form action="../albums/upload" class="form-horizontal" method="post" enctype="multipart/form-data">

Categories