How to insert custom data in database using Opencart - insert

Am creating my store using Opencart. Here am creating a custom page called sales_performance.
Am trying to insert some value in database.
But i can't insert the data, how can i do that?.
And also it not showing error
Following my code:
Controller
sales_performance.php
<?php
class ControllerProductSalesPerformance extends Controller
{
private $error = array();
private $data = array();
public function index()
{
$this->load->language('product/allproduct');
$this->document->setTitle($this->language->get('Sales Performance'));
$this->load->model('catalog/allproduct');
$data['action']=$this->url->link('product/sales_performance','','SSL');
$this->data['text_list'] = $this->language->get('text_list');
$this->data['text_no_results'] = $this->language->get('text_no_results');
$this->data['text_confirm'] = $this->language->get('text_confirm');
$this->data['text_missing'] = $this->language->get('text_missing');
$this->data['column_order_id'] = $this->language->get('column_order_id');
$this->data['column_customer'] = $this->language->get('column_customer');
$this->data['column_status'] = $this->language->get('column_status');
$this->data['column_total'] = $this->language->get('column_total');
$this->data['column_date_added'] = $this->language->get('column_date_added');
$this->data['column_date_modified'] = $this->language->get('column_date_modified');
$this->data['column_action'] = $this->language->get('column_action');
$this->data['entry_return_id'] = $this->language->get('entry_return_id');
$this->data['entry_order_id'] = $this->language->get('entry_order_id');
$this->data['entry_customer'] = $this->language->get('entry_customer');
$this->data['entry_order_status'] = $this->language->get('entry_order_status');
$this->data['entry_total'] = $this->language->get('entry_total');
$this->data['entry_date_added'] = $this->language->get('entry_date_added');
$this->data['entry_date_modified'] = $this->language->get('entry_date_modified');
$this->data['button_invoice_print'] = $this->language->get('button_invoice_print');
$this->data['button_shipping_print'] = $this->language->get('button_shipping_print');
$this->data['button_add'] = $this->language->get('button_add');
$this->data['button_edit'] = $this->language->get('button_edit');
$this->data['button_delete'] = $this->language->get('button_delete');
$this->data['button_filter'] = $this->language->get('button_filter');
$this->data['button_view'] = $this->language->get('button_view');
//$data['token'] = $this->session->data['token'];
$pagination = new Pagination();
//$pagination->total = $order_total;
//$pagination->page = $page;
$data['pagination'] = $pagination->render();
$this->data['sort'] = $sort;
$this->data['order'] = $order;
$this->data['header'] = $this->load->controller('common/header');
$this->data['column_left'] = $this->load->controller('common/column_left');
$this->data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('default/template/product/sales_performance.tpl', $this->data));
}
public function insertSelectedCustomer()
{
#####Add sales persion achievement####
if ($this->request->server['REQUEST_METHOD'] == 'POST')
{
$date = $_GET['date'];
$sales_person_id = $_GET['sales_person_id'];
$sales_person_name = $_GET['sales_person_name'];
$customer_id = $_GET['customer_id'];
$customer_name = $_GET['customer_name'];
$achievement = $_GET['achievement'];
$query = $this->db->query("insert into ".DB_PREFIX."sales_person_achievement('date') value('".$date."')");
if($query==false)
{
echo ''.mysql_error();
}
}
##### Add sales persion achievement ####
}
}
This is my tpl file
sales_performance.tpl
<form action="<?php echo $action; ?>" method="POST" class="form-inline" enctype="multipart/form-data">
<div class="form-group">
<label for="">Select Date:</label>
<input type="text" name="date" id="datepicker" class="form-control" placeholder="Select Date">
<input type="hidden" name="sales_person_id" value="<?php echo $sales_person1['customer_id']; ?>">
<input type="hidden" name="sales_person_name" value="<?php echo $sales_person1['name']; ?>">
<input type="hidden" name="customer_id" value="<?php echo $customer['customer_id'];; ?>">
<input type="hidden" name="customer_name" value="<?php echo $customer['name'];; ?>">
</div>
<div class="form-group">
<label for="">Fill Achievement Amonut:</label>
<input type="number" name="achievement" class="form-control" placeholder="Achievement Amount">
</div>
<div class="form-group">
<input type="submit" id="saveachievement" name="save" class="btn btn-primary">
</div>
</form>
<script type="text/javascript">
$('#saveachievement').on('click', function() {
var date = document.getElementsByName('date')[0].value;
var sales_person_id = document.getElementsByName('sales_person_id')[0].value;
var sales_person_name = document.getElementsByName('sales_person_name')[0].value;
var customer_id = document.getElementsByName('customer_id')[0].value;
var customer_name = document.getElementsByName('customer_name')[0].value;
var achievement = document.getElementsByName('achievement')[0].value;
//alert(achievement);
location="index.php?route=product/sales_performance&sales_person_id="+sales_person_id+"&customer_id="+customer_id;
});
</script>

Actually am miss spelling for value
$query = $this->db->query("insert into ".DB_PREFIX."sales_person_achievement('date') value('".$date."')");
change To
$query = $this->db->query("insert into ".DB_PREFIX."sales_person_achievement('date') values('".$date."')");
i mean value change to values
Now its working.

Related

Image is not uploading in CI

I am new in CI and I am trying to upload image but dont know why its not uploading,
Here is my view,
<form action="<?php echo site_url('admin/test/'.$param2.'/add'); ?>" enctype="multipart/form-data" method="post" id = 'mcq_form'>
<input type="hidden" name="question_type" value="mcq">
<div class="input-group">
<div class="custom-file">
<input type="file" class="custom-file-input" id="attachment" name="attachment" onchange="changeTitleOfImageUploader(this)">
<label class="custom-file-label" for="attachment"><?php echo get_phrase('attachment'); ?></label>
</div>
</div>
<div class="text-center">
<button class = "btn btn-success" id = "submitButton" type="button" name="button" data-dismiss="modal"><?php echo get_phrase('submit'); ?></button>
</div>
</form>
<script>
$('#submitButton').click( function(event) {
$.ajax({
url: '<?php echo site_url('admin/test/'.$param2.'/add'); ?>',
type: 'post',
data: $('form#mcq_form').serialize(),
success: function(response) {
if (response == 1) {
success_notify('<?php echo get_phrase('question_has_been_added'); ?>');
}else {
error_notify('<?php echo get_phrase('no_options_can_be_blank_and_there_has_to_be_atleast_one_answer'); ?>');
}
}
});
showLargeModal('<?php echo site_url('modal/popup/test/'.$param2); ?>', '<?php echo get_phrase('test'); ?>');
});
</script>
on Controller I am trying to get image data but dont know why its not fetching,
print_r($_FILES['attachment']['name']);
die();
I don't understand, what I am missing. Please help me out.
You can try it like this
<input type="file" name="logo" class="form-control" value="">
in your controller
$logo = '';
if (!empty($_FILES['logo']['name'])) {
/* Conf Image */
$file_name = 'profile_' . time() . rand(100, 999);
$configImg['upload_path'] = './uploads/profile/';
$configImg['file_name'] = $file_name;
$configImg['allowed_types'] = 'png|jpg|jpeg';
$configImg['max_size'] = 2000;
$configImg['max_width'] = 2000;
$configImg['max_height'] = 2000;
$configImg['file_ext_tolower'] = TRUE;
$configImg['remove_spaces'] = TRUE;
$this->load->library('upload', $configImg, 'logo');
if ($this->logo->do_upload('logo')) {
$uploadData = $this->logo->data();
$logo = 'uploads/profile/' . $uploadData['file_name'];
} else {
$this->custom_errors['logo'] = $this->logo->display_errors('', '');
}
}

Laravel insert multiple records in pivot table from arrays

I'm trying to save multiple records(rows) in a table. The html fields are dynamic fields and declared as array, so they can be 1, 2 or more.
My blade:
<div class="col-md-12" id="inputFormRow" style="padding-left: 0px;">
<div class="input-group mb-3">
<input type="text" name="tableName[]" class="form-control m-input" placeholder="Name" autocomplete="off">
<input type="text" name="fromNr[]" class="form-control m-input" placeholder="From" autocomplete="off">
<input type="text" name="toNr[]" class="form-control m-input" placeholder="to" autocomplete="off">
<div class="input-group-append">
<button id="removeRow" type="button" class="btn btn-danger">X</button>
</div>
</div>
+
My JS to create dynamic fields:
$("#addRow").click(function () {
var html = '';
html += '<div class="col-md-12" id="inputFormRow" style="padding-left: 0px;">';
html += '<div class="input-group mb-3">';
html += '<input type="text" name="tableName[]" class="form-control m-input" placeholder="Name" autocomplete="off">';
html += '<input type="text" name="fromNr[]" class="form-control m-input" laceholder="From" autocomplete="off">';
html += '<input type="text" name="toNr[]" class="form-control m-input" placeholder="To" autocomplete="off">';
html += '<div class="input-group-append">';
html += '<button id="removeRow" type="button" class="btn btn-danger">X</button>';
html += '</div>';
html += '</div>';
$('#newRow').append(html);
});
My Offer.php Model:
protected $fillable = ['some columns];
public function table()
{
return $this->hasMany(Table::class);
}
My Table.php Model:
protected $fillable = ['offer_id','tableName','fromNr','toNr'];
public function offer()
{
return $this->hasMany(Offer::class);
}
Now, in my Controller, I have to get request input values and then save into Table table. The input values can be more than 1 and dynamically.
My tries:
public function store(Request $request)
{
$statement = DB::select("SHOW TABLE STATUS LIKE 'offer'");
$nextId = $statement[0]->Auto_increment;
$tableName = $request->get('tableName');
$fromNr = $request->get('fromNr');
$toNr = $request->get('toNr');
$offer = Offer::find($nextId);
$offer->table()->saveMany([
new Table(['restaurant_offer_id' => $nextId]),
new Table(['tableName' => $tableName]),
new Table(['fromNr' => $fromNr]),
new Table(['toNr' => $toNr]),
]);
}
Thank you in Advance.
If you want to make it dynamic you have to loop over the input array.
$tables = [];
foreach($tableName as $key => $value) {
$table = new Table;
$table->tableName = $tableName[$key];
$table->fromNr = $fromNr[$key];
$table->toNr = $toNr[$key];
$tables[] = $table;
}
$offer->table()->saveMany($tables);
If you use name="example[]" on the view, you are receiving the variable as an array in the controller. Also if you use Eloquent Model binding you can save the model instance to the database with simpler syntax.
Try something like this in the controller:
public function store(Request $request)
{
foreach($request->tableName as $key => $tableName)
{
Offer::create(['tableName' => $tableName',
'fromNr' => $request->fromNr[$key],
'toNr' => $request->toNr[$key]])
}
}
Additionally I recommend to use plural naming in case of arrays. Like tableNames, fromNrs. So you know that it should contain multiple variables.

[Codeigniter]Multiple upload cant insert to database and not uploading to directory

How to upload multiple images with Codeigniter 4.x ?
I tried to loop the do_upload function in my model but it's not working, and I tried another code that I got from GitHub but still, none of it works.
This is my view:
<div class="section-body">
<h2 class="section-title">Entry Group Passanger</h2>
<div class="row">
<div class="col-md-12">
<form action="<?= base_url('passanger/addgroup') ?>" method="POST" enctype="multipart/form-data">
<?php for($i=1;$i<=$pax['pax'];$i++) : ?>
<h5>Passanger ke-<?= $i ?></h5>
<div class="form-row">
<div class="col-md-6">
<label for="fullname">Fullname</label>
<input type="text" class="form-control" name="name[]">
<?= form_error('name', '<small class="text-danger pl-3">', '</small>'); ?>
</div>
<div class="col-md-6">
<label for="gender">Gender</label>
<select class="form-control select2-input" name="gender">
<option>-- Select Gender --</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select>
<?= form_error('gender', '<small class="text-danger pl-3">', '</small>'); ?>
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-4 mt-2">
<label for="">Upload Passport</label>
<input type="file" name="upload_passport[]" id="input-file-now" class="dropify" />
</div>
</div>
this is my model :
public function addGroup()
{
$user = $this->db->get_where('user', ['username' => $this->session->userdata('username')])->row_array();
$pax = $this->getPaxById();
date_default_timezone_set('Asia/Jakarta');
$upload_image = $_FILES['upload_passport[]']['name'];
if ($upload_image) {
$config['upload_path'] = './assets/img/uploads/passport';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
for($i=0;$i<$pax['pax'];$i++) {
if ($this->upload->do_upload('upload_passport[$i]')) {
$new_image = $this->upload->data('file_name');
} else {
echo $this->upload->display_errors();
}
}
}
$name = $this->input->post("name[]");
$gender = $this->input->post("gender[]");
$birthdate = $this->input->post("birthdate[]");
$no_passport = $this->input->post("no_passport[]");
$expire_passport = $this->input->post("expire_passport[]");
$destination = $this->input->post("destination[]");
$date = $this->input->post("date[]");
$dp1 = "0";
$dp2 = "0";
$lunas = "0";
$type = "Group";
$status = "Not Complete";
$permission = "0";
$upload_passport = $new_image;
$upload_dp1 = "default.png";
$upload_dp2 = "default.png";
$date_created = date('d/m/Y H:i:s');
$data = [];
$jumlah = $pax['pax'];
for($x=0;$x<$jumlah;$x++) {
array_push($data, [
'name'=>$this->input->post("name[$x]"),
'id_user'=> $user['id_user'],
'gender'=>$this->input->post("gender[$x]"),
'birthdate'=>$this->input->post("birthdate[$x]"),
'no_passport'=> $this->input->post("no_passport[$x]"),
'expire_passport'=> $this->input->post("expire_passport[$x]"),
'destination'=> $this->input->post("destination[$x]"),
'date'=> $this->input->post("date[$x]"),
'dp1'=> $dp1,
'dp2'=> $dp2,
'lunas'=> $lunas,
'pax'=> $pax['pax'],
'type'=> $type,
'status'=> $status,
'permission'=> $permission,
'upload_passport'=> $new_image,
'upload_dp1'=> $upload_dp1,
'upload_dp2'=> $upload_dp2,
'date_created'=> $date_created
]);
var_dump($data); die;
}
$this->db->insert_batch("passanger", $data);
}
What I want to get is:
array('','','upload_image'), array('','','upload_image')
When insert it to database but when I do it the upload just gets output null and it's not even uploaded to my uploads directory. I would really appreciate it if you help me, I've been stuck on this for 3 days. Thank you.
for ($i=0; $i < sizeof($_FILES['image']['name']) ; $i++) {
$_FILES['file']['name'] = $_FILES['image']['name'][$i];
$_FILES['file']['type'] = $_FILES['image']['type'][$i];
$_FILES['file']['tmp_name'] = $_FILES['image']['tmp_name'[$i];
$_FILES['file']['error'] = $_FILES['image']['error'][$i];
$_FILES['file']['size'] = $_FILES['image']['size'][$i];
$config['upload_path'] = PRODUCT_IMAGE_UPLOAD_PATH;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ($this->upload->do_upload('file')){
$images[] = $this->upload->data('file_name');
}else {
echo $this->upload->display_errors();
}
}
Try this in Codeigniter 4
in your controller add this
$image_model = new App\Models\Images(); // Your model name that is load your model
if($imagefiles = $this->request->getFiles())
{
foreach($imagefiles['uploadImages'] as $img)
{
if ($img->isValid() && ! $img->hasMoved())
{
$image_name = $img->getRandomName(); // This is applicable if you want to change the name of the images
if($image_model->save_images($image_name))
{
$img->move(WRITEPATH.'uploads/images/ads', $image_name); // WRITEPATH.'uploads/images/ads' is the part you wish to save you file to
}
}
}
}
In your Model e.g Image model i have a method call save_images()as this
use Codeigniter\Model
class Images extends Model{
public function save_images($image = '')
{
// We set the column 'name' to be allow for data entry into the db. note this is mandatory for now.
// hope it will change in feature. 'name' is the column in database table where you will save the image name
// this command the CI4 db to select only the image column in the database table
$this->allowedFields = ['name'];
return $this->db->table('images')->insert(['name' => $image]);
// echo $sql = $this->db->getLastQuery();
}
}
Then in your html file input, do this
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="uploadImages[]" multiple>
</div>
</form>
I hope this will work for you

Laravel checkbox implementation for updating database

I've been trying to make an attendance management system in Laravel.
In the attendance view,when a checkbox is checked ,the controller function is supposed to increment the appropriate database column.
I've been having some issues.Here's my code:
views:
<div class="container">
<!--<div class="row">-->
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Take Attendance</div>
<h4><center>Teacher: {{ auth()->user()->name}}</center></h4>
<div class="form-inline">
#foreach ($second as $sec)
<br>
<div class = "form-group">
{{$sec->Roll }}
&nbsp&nbsp&nbsp&nbsp
{{ $sec->Name}}
</div>
<div class = "form-group">
<!--{{Form::checkbox('agree') }}-->
<input tabindex="1" type="checkbox" value="{{$sec->Roll}}" name="" />
</div>
#endforeach
</div>
<br>
<form action ="report_generate&<?php echo $name ?>" method = "post" enctype = "multipart/form-data" >
<!--<input type = "hidden" name = "_token" value = "{{{ csrf_token() }}}"/>-->
<div class = "form-group">
<input type="submit" value= "Submit">
<center>Report</center>
</div>
</form>
</div>
</div>
</div>
Controller(for submit button):
public function report_generate($tabu)
{
$year = DB::table('sub')->select('Year')-
>where('sub.Subject_Name','=',$tabu)->get();
$sub_id = DB::table('sub')->select('Subject_Id')-
>where('sub.Subject_Name','=',$tabu)->get();
ob_start();
echo $year;
$output=ob_get_contents();
ob_end_clean();
if ( $output=='[{"Year":1}]')
{
$req = "first";
}
elseif ( $output=='[{"Year":2}]')
{
$req = "second";
}
elseif ( $output=='[{"Year":3}]')
{
$req = "third";
}
elseif ( $output=='[{"Year":4}]')
{
$req = "fourth";
}
$final = DB::table($req)->get();
//dd($final);
//$columns = Schema::getColumnListing($req);
//dd($sub_id);
ob_start();
echo $sub_id;
//dd($sub_id);
$va=ob_get_clean();
$va = stripslashes($va);
$txt = rtrim($va,"}]");
$txt = ltrim($txt,"[{Subject_Id:");
$txt = ltrim($txt,"Subject_Id:");
$txt = explode(":",$txt);
$txt = str_replace('"','', $txt);
//dd($txt[1]);
$columns = Schema::getColumnListing($req);
//dd($columns);
//dd($txt);
foreach ($columns as $col)
{
//dd("Y");
if($col == $txt[1])
{
$got=DB::table($req)->select($col)->get();
//dd($got);
foreach($got as $g)
{
//want to increment that cell value
}
}
}
}
Looks like your checkboxs are outside of the form divs which is an issue. You also seem to be skipping over the Laravel features, for example having a Sub Model you can call on, or using the Request facade. Also not sure why you're using ob for those string comparisons (might actually want to look at Switch for that long elseif block) Lastly, you might want to to use a raw DB statement to do the increments within a SQL query
DB::statement("UPDATE " . $table . " set " . $column . " to " . $column . " + 1 WHERE id IN (" implode(', ', $ids) . ')")

how search between date using post in codeignitier

Dear Expert need Help first see my view code in codeigniter :
<div class="form-group">
<label for="tglawal" class="col-sm-2 control-label">Periode</label>
<div class="col-sm-3">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="date" class="form-control" name="tglawal" id="tglawal">
</div>
</div>
<div class="col-sm-3">
<div class="input-group date">
<div class="input-group-addon">
<i class="fa fa-calendar"></i>
</div>
<input type="date" class="form-control" name="tglakhir" id="tglawal1">
</div>
</div>
</div>
and this my model code :
private function _get_datatables_query()
{
//add custom filter here
if($this->input->post('tglawal'))
{
$this->db->where('b.tglawal', $this->input->post('tglawal'));
}
if($this->input->post('tglakhir'))
{
$this->db->where('b.tglakhir', $this->input->post('tglakhir'));
}
}
public function get_datatables()
{
$this->_get_datatables_query();
if($_POST['length'] != -1)
$this->db->limit($_POST['length'], $_POST['start']);
$query = $this->db->get();
return $query->result();
}
and my controller if i get the important code is:
public function index()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->view('infokunjungan_view', $data);
}
else redirect(base_url());
}
public function ajax_list()
{
$list = $this->Infokunjungan->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $infokunjungan) {
$no++;
$row = array();
$row[] = "<td style='vertical-align:middle'><center>{$no}<center></td>";
$row[] = "<td style='font-size:9px; vertical-align:left;'>{$infokunjungan->tglawal}<center></td>";
$row[] = "<td style='font-size:9px; vertical-align:left;'>{$infokunjungan->tglakhir}<center></td>";
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->Infokunjungan->count_all(),
"recordsFiltered" => $this->Infokunjungan->count_filtered(),
"data" => $data,
);
//output to json format
echo json_encode($output);
}
the problem is if searching between two date tglawal and tglakhir
im using between 2016-12-04 and 2016-12-04 output display will empty
but if using between 2016-12-04 and 2016-12-06 output success where is my problem or maybe im using where or i have to use like?
You need to use the >= and <= operator.
In your model try the below.
if($this->input->post('tglawal'))
{
$this->db->where('b.tglawal >=', $this->input->post('tglawal')); //assuming this is your begining (from) date
}
if($this->input->post('tglakhir'))
{
$this->db->where('b.tglakhir <=', $this->input->post('tglakhir')); //assuming this is your end(to) date
}
The above will search for the between dates including the dates selected.
Use the operator depending on the beginning and ending variable.

Resources