Insert data excel into 2 tables with id codeigniter - mysql

I have a problem with how to upload files excel with phpsreadsheet to the database. I want to put the data into two tables namely:
Beasiswa contain table: beasiswa_nama, beasiswa_id, beasiswa_file (link file), beasiswa_tahun, DATE_CREATED, DATE_UPDATED.
data_mahasiswa table cotain table: id_mhs, nama_mhs, nim_mhs, (FK) id_beasiswa
How to insert a file and read it to the Beasiswa table, and student data to data_mahasiswa?
Relation table:
Error create data:
Beasiswa Controller
public function create()
{
$this->form_validation->set_rules('nama_beasiswa', 'Nama Beasiswa', 'trim|required');
$this->form_validation->set_rules('tahun_beasiswa', 'Tahun Mahasiswa', 'trim|required');
if (empty($_FILES['nama_mahasiswa_beasiswa']['name'])) {
$this->form_validation->set_rules('nama_mahasiswa_beasiswa', 'File Nama Mahasiswa', 'required');
}
if ($this->form_validation->run() == TRUE) {
// true case
$upload_nama_mahasiswa = $this->_upload_nama_mahasiswa();
$data = array(
'beasiswa_nama' => htmlspecialchars($this->input->post('nama_beasiswa', true)),
'beasiswa_tahun' => htmlspecialchars($this->input->post('tahun_beasiswa', true)),
'beasiswa_file' => $upload_nama_mahasiswa,
'date_created' => date("Y-m-d H:i:s")
);
$create = $this->m_beasiswa->create($data);
if ($create == true) {
$this->session->set_flashdata('success', 'Berhasil Upload Data Beasiswa');
redirect('beasiswa/', 'refresh');
} else {
$this->session->set_flashdata('errors', 'Terjadi Galat. Silahkan Periksa Kembali!!');
redirect('beasiswa/create', 'refresh');
}
} else {
$this->render_template('beasiswa/create', $this->data);
}
}
private function _upload_nama_mahasiswa()
{
$filename = 'import-data';
$config['upload_path'] = 'assets/file/beasiswa/';
$config['file_name'] = $filename;
$config['overwrite'] = TRUE;
$config['allowed_types'] = 'xlsx|xls';
$config['max_size'] = '1024';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('nama_mahasiswa_beasiswa')) {
// $error = array('errors' => $this->upload->display_errors('File yang anda masukkan tidak sesuai permintaan, atau file terlalu besar.'));
$this->session->set_flashdata('errors', 'File yang anda masukkan tidak sesuai permintaan, atau file terlalu besar.');
redirect('beasiswa/create', 'refresh');
} else {
$data = array('upload_data' => $this->upload->data());
$img = $data['upload_data']['file_name'];
$excelReader = new PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$loadExcel = $excelReader->load($config['upload_path'] . $img);
$sheet = $loadExcel->getActiveSheet()->toArray(null, true, true, true);
$dataExcel = array();
// $this->data['sheet'] = $sheet;
$numRow = 3;
foreach ($sheet as $row) {
if ($numRow > 3) {
array_push(
$dataExcel,
[
'nama_mhs' => $row['A'],
'nim_mhs' => $row['B']
]
);
}
$numRow++;
}
$this->db->insert_batch('data_beasiswa', $dataExcel);
unlink($config['upload_path'] . $img);
}
}
Beasiswa Model
public function create($data)
{
if ($data) {
$insert = $this->db->insert('beasiswa', $data);
return ($insert == true) ? true : false;
}
}
Beasiswa View
<?php
defined('BASEPATH') or exit('No direct script access allowed');
?>
<!-- Main Content -->
<div class="main-content">
<section class="section">
<div class="section-header">
<div class="section-header-back">
<i class="fas fa-arrow-left"></i>
</div>
<h1>Tambah Beasiswa</h1>
</div>
<div class="section-body">
<div class="row">
<div class="col-md-12 col-xs-12 col-xl-12 col-12">
<div id="messages"></div>
<?php if ($this->session->flashdata('success')) : ?>
<div class="alert alert-success alert-dismissible">
<div class="alert-body">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<?php echo $this->session->flashdata('success'); ?>
</div>
</div>
<?php elseif ($this->session->flashdata('errors')) : ?>
<div class="alert alert-danger alert-dismissible show fade">
<div class="alert-body">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<?php echo $this->session->flashdata('errors'); ?>
</div>
</div>
<?php endif; ?>
<div class="card">
<div class="card-body">
<b style="font-size: 17px">Unduh format excel data mahasiswa</b><br>
Download template
<form action="<?php base_url('beasiswa/create') ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<div class="section-title">Nama Program Beasiswa</div>
<input type="text" class="form-control" name="nama_beasiswa" id="nama_beasiswa" placeholder="Nama Program Beasiswa" value="<?= set_value('nama_beasiswa'); ?>">
<?= form_error('nama_beasiswa', '<small class="text-danger">', '</small>'); ?>
</div>
<div class="form-group">
<div class="section-title">Tahun Beasiswa</div>
<input type="text" class="form-control" name="tahun_beasiswa" id="tahun_beasiswa" placeholder="Tahun Beasiswa (contoh: 2020)" value="<?= set_value('tahun_beasiswa'); ?>">
<?= form_error('tahun_beasiswa', '<small class="text-danger">', '</small>'); ?>
</div>
<div class="form-group">
<div class="section-title">Upload File Nama Mahasiswa</div>
<input type="file" name="nama_mahasiswa_beasiswa" id="nama_mahasiswa_beasiswa" class="form-control col-sm-6 col-md-6">
<p class="text-danger" style="font-style:italic"><b>* Upload file sesuai dengan format yang sudah disesuaikan</b></p>
</div>
<button type="submit" class="btn btn-primary">Simpan</button>
Kembali
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</div>

It is because foreign key error probably happening because you insert a null data in data_mahasiswa table.
There was empty space in your excel (that probably have been edited?) that are used in foreach ($sheet as $row). You can fix this with:
foreach ($sheet as $row) {
if ($numRow > 3) {
if($row['A'] != null && $row['B'] != null)
{
$dataExcel[] = array(
'nama_mhs' => $row['A'],
'nim_mhs' => $row['B']
);
}
/*you can also break the function, if no empty row between data in your excel*/
/*else
{
break;
}*/
}
}

you need to get rid of the null value when you input the data to the database. above this line of your code at Beasiswa Controller
$this->db->insert_batch('data_beasiswa', $dataExcel);
add this line of code to delete cell that have null data
foreach ($dataExcel as $data => $val) {
if(empty($val['nama_mhs'])){
unset($dataExcel[$data]['nama_mhs']);
unset($dataExcel[$data]['nim_mhs']);
}
}
$dataExcel = array_filter($dataExcel);
$data = array('data_excel' => $dataExcel);

Related

How to just use json and ajx for Realtime notification in laravel 9

I have a function here which is needed to generate ticket. What is working rights is when Generating a ticket, it also creates a notification, but it was not real-time showing in the notification bell.
After a search, I found that using post-json and ajax is feasible. But I just started learning programming so I have zero knowledge about these two technologies. I hope someone can provide me with some help on how to use them.
PS. I also found that web socket and pusher are also viable solutions, but since my system only has few functions that need to send notifications. So I don't take websocket and pusher into consideration.
Translated with www.DeepL.com/Translator (free version)
I would like to attach my code below and hope somebody could help me. Any suggestion is highly appreciated. Thankyou in advance
In my controller
public function GenerateTicket($code)
{
# Retrieve the records using $code
$GiftGiving = GiftGiving::where('code', $code)->firstOrFail();
$tickets = GiftGivingBeneficiary::where('gift_giving_id', $GiftGiving->id)->get();
# Users can only access their own charity's records
if ($GiftGiving->charitable_organization_id == Auth::user()->charitable_organization_id) {
# Must have at least one beneficiary before generating tickets
if ($tickets->count() < 1) {
$notification = array(
'message' => 'Gift Giving must have at least one (1) beneficiary first before generating tickets',
'alert-type' => 'error'
);
return redirect()->back()->with($notification);
}
# Retrieve the last batch no. from the gift giving.
$batch_no = $GiftGiving->batch_no;
# Increment Batch no. by +1
$GiftGiving->update([
'last_downloaded_by' => Auth::id(),
'batch_no' => $batch_no + 1,
]);
$pdf = PDF::loadView('charity.gifts.generate_ticket', compact('tickets'));
# Audit Logs Creation
$log = new AuditLog;
$log->user_id = Auth::user()->id;
$log->action_type = 'GENERATE PDF';
$log->charitable_organization_id = Auth::user()->charitable_organization_id;
$log->table_name = 'Gift Giving';
$log->record_id = $GiftGiving->code;
$log->action = 'Charity Admin generated tickets for the Gift Giving [' . $GiftGiving->name . '] with batch no. ' . $GiftGiving->batch_no . '.';
$log->performed_at = Carbon::now();
$log->save();
# Send Notification to each user in their Charitable Organizations
$users = User::where('charitable_organization_id', Auth::user()->charitable_organization_id)->where('status', 'Active')->get();
foreach ($users as $user) {
Notification::insert([
'code' => Str::uuid()->toString(),
'user_id' => $user->id,
'category' => 'Gift Giving',
'Subject' => 'Generated Tickets',
'message' => Auth::user()->role . ' ' . Auth::user()->info->first_name . ' ' . Auth::user()->info->last_name . ' has generated tickets for ['.$GiftGiving->name.'] with batch no. ' . $GiftGiving->batch_no . '.',
'icon' => 'mdi mdi-ticket',
'color' => 'info',
'created_at' => Carbon::now(),
]);
}
return $pdf->download($GiftGiving->name . ' - No. ' . $batch_no . '.pdf');
} else {
$notification = array(
'message' => 'Users can only access their own charity records.',
'alert-type' => 'error'
);
return redirect()->back()->with($notification);
}
}
The view for the header
<div class="dropdown-menu dropdown-menu-lg dropdown-menu-end p-0"
aria-labelledby="page-header-notifications-dropdown">
<div class="p-3">
<div class="row align-items-center">
<div class="col">
<h6 class="m-0"> Notifications </h6>
</div>
<div class="col-auto">
View All
</div>
</div>
</div>
#include('charity.body.notifications')
<div class="p-2 border-top">
<div class="d-grid">
<a class="btn btn-sm btn-link font-size-14 text-center" href="{{ route('notifications.all') }}">
<i class="mdi mdi-arrow-right-circle me-1"></i> View all..
</a>
</div>
</div>
</div>
</div>
THe view for notification
#php
$notifications = App\Models\Notification::latest()->limit(3)->get();
#endphp
<div data-simplebar style="max-height: 230px;">
#if(Auth::user()->notifications->count() == 0)
<p class="text-muted font-size-12 text-center">You have no new notifications.</p>
#endif
#foreach (Auth::user()->notifications as $notif)
<a href="{{ route('notifications.view' , $notif->code) }}" class="text-reset notification-item">
<div class="d-flex">
<div class="avatar-xs me-3">
<span class="avatar-title bg-{{$notif->color}} rounded-circle font-size-16">
<i class="{{$notif->icon}}"></i>
</span>
</div>
<div class="flex-1">
<h6 class="mb-1">{{ $notif->subject}} #if($notif->read_status == 'unread')<span class="badge bg-danger">NEW</span>#endif</h6>
<div class="font-size-12 text-muted">
<p class="mb-1">{{Str::limit($notif->message, 75)}}</p>
<p class="mb-0"><i class="mdi mdi-clock-outline"></i> {{Carbon\Carbon::parse($notif->created_at)->diffForHumans()}}</p>
</div>
</div>
</div>
</a>
#endforeach
</div>

Yii2 Pjax delete action with modal

I'm trying to do a delete action with Pjax (without refreshing the page).
The register is deleted properly, page no reloads, BUT, if immediately I try to delete another record, don't load the modal.
So the delete button cannot call to modal for new delete.
I hope you can help me to resolve this. Thanks
Here is my code:
Step 1
file: index view
<?php Pjax::begin(['id' => 'pjax-container']); ?>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
.....
'columns' => [
...others columns
[
'class' => 'yii\grid\ActionColumn',
'template' => '{view} {delete}',
'buttons' => [
'delete' => function ($url, $model, $key) {
return Html::a(
'<span class="material-icons">delete</span>',
'javascript:void(0)',
[
'data-ruta' => Url::toRoute(['delete', 'id' => $model->id]),
'id' => $model->id,
'class' => 'btn-eliminar-competencia option-danger',
'title' => __('GxP', 'commons.delete'),
'aria-label' => "Eliminar",
'data-pjax' => "0",
'data-method' => "post"
]
) . '</div>';
}
]
]
]
]);
?>
<?php Pjax::end(); ?>
Step 2
file index view
After clicking the delete button, go to open modal
<div class="modal bootstrap-dialog" role="dialog" aria-hidden="true" id="modal-eliminar-
competencia" aria-labelledby="w3_title" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title"><?= __('GxP', 'commons.delete') ?></h4>
</div>
<div class="modal-body text-center">
<div class="bootstrap-dialog-message"><?= __('GxP', 'dialogs.sure_delete_element') ?></div>
<div id="text-modal-competencia"></div>
</div>
<div class="modal-footer text-center">
<button class="btn btn-success" data-dismiss="modal">
<?= __('GxP', 'commons.cancel') ?>
</button>
<button class="btn btn-primary btn-modal-eliminar-competencia">
<?= __('GxP', 'commons.accept') ?>
</button>
</div>
</div>
</div>
</div>
Step 3
file: index.js
$(document).ready(function(){
var ruta
eliminar = 0
redirect = 0
modal = $('#modal-eliminar-competencia')
modal_competencia = $('#modal-competencia')
$('.div2').click(function(){
window.location = $('#tipos-competencias').attr('href')
})
$('.btn-eliminar-competencia').click(function(){
eliminar = $(this).attr('data-ruta')
$('#text-modal-competencia').html('')
id = $(this).attr('id')
$.ajax({
type:'post',
url:'/competences/competences-asociated',
data:{id:id},
dataType:'json'
})
.done(function(r){
console.log(r)
mensaje_text =
'<br>'+
'<p>'+__('commons.info')+':</p>'+
'<small>'+
r.positions+__('dialogs.associated_positions')+
'</small>'+
'<br>'+
'<small>'+
r.reagents+__('dialogs.associated_reagents')+
'</small>';
$('#text-modal-competencia').html(mensaje_text)
})
.fail(function(){
})
modal.modal({backdrop:'static',keyboard:true})
})
// here resolve the delete item and reload container with Pjax
$('.btn-modal-eliminar-competencia').click(function(){
$.ajax({
type:'post',
url:eliminar,
dataType:'json',
success:function(response){
if(response.code == 204){
redirect = response.redirect
$('.message-contenido .message-text').html(__('dialogs.success_delete'))
modal.modal('hide')
$('.capa').show()
$('.message-action').show()
ruta = false
$.pjax.reload({container:'#pjax-container'})
}
else{
modal_alert(__('dialogs.unespected_error'))
}
}
})
})
})

Upload multiple forms no save in mysql database laravel 9

could someone help me to find the error? only the post_image input is saved the others are not saved in the database what am I doing wrong?
I've checked it several times but only the filename of the post_image field is saved in the database, the other files are not persisting in the database, could someone help me where I'm going wrong?
Every help is welcome.
Thank you very much in advance.
create.blade.php
div class="form-group row">
<label for="post_image" class="col-md-4 col-form-label text-md-right">{{ __('Image') }}</label>
<div class="col-md-6">
<input type="file" name="post_image"/>
#error('post_image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<br>
<hr>
<label for="post_video" class="col-md-4 col-form-label text-md-right">{{ __('Video') }}</label>
<div class="col-md-6">
<input type="file" name="post_video"/>
#error('post_video')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<br>
<hr>
<label for="post_gif" class="col-md-4 col-form-label text-md-right">{{ __('GIF') }}</label>
<div class="col-md-6">
<input type="file" name="post_gif"/>
#error('post_gif')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<br>
<hr>
</div>
function store in controller -->
public function store(Request $request, Community $community)
{
$user = Auth::user();
$creds = $request->validate([
'post_image' => '|image|mimes:jpeg,jpg,png,svg|max:18048',
'post_video' => 'mimes:mp4,ogx,oga,ogv,ogg,webm|max:180048',
'post_gif' => '|image|mimes:gif|max:18048',
'title' => ['required'],
'post_text' => ['required'],
'post_url' => ['required']
]);
//IMAGE JPG,PNG,SVG
if ($image = $request->file('post_image')) {
$destinationPath = 'media/uploads';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$input['post_image'] = "$profileImage";
}
//END IMAGE JPG,PNG,SVG
//VIDEO MP4
if ($image = $request->file('post_video')) {
$destinationPath = 'media/uploads';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$inputmp4 ['post_video'] = "$profileImage";
}
//END VIDEOS
// GIF IMAGES
if ($image = $request->file('post_gif')) {
$destinationPath = 'media/uploads';
$profileImage = date('YmdHis') . "." . $image->getClientOriginalExtension();
$image->move($destinationPath, $profileImage);
$inputgif ['post_gif'] = "$profileImage";
}
//END GIF IMAGES
$post = $community->posts()->create
(['user_id' => auth()->id(),
'title' => $creds['title'],
'post_text' => $creds['post_text'],
'post_url' => $creds['post_url'],
'post_image' => $input['post_image'] ?? '',
'post_video' => $inputmp4['post_video'] ?? '',
'post_gif' => $inputgif['post_gif'] ?? '',
]);
return redirect()->route('communities.show', $community);
}
Is it possible post_video and post_gif are empty? Php has a max_upload and max post size limit that is defined on the ini file. It is possible that that size is being exceeded. Hence your files are not actually uploading.
Also, your if statements are kinda confusing. Check this out :
//This if statement will always return true. Since you're assigning $image variable to $request->file('post_video').
if ($image = $request->file('post_video')) {
//Code For saving file
//Don't use this
}
// Instead you should use hasFile to check if the file is uploaded. here's how
if ($request->hasFile('post_video')) {
$video = $request->file('post_video');
//Code For saving file
//Use This instead
}
Also, at the last line, where you call create() method, do this:
$post = $community->posts()->create
(['user_id' => auth()->id(),
'title' => $creds['title'],
'post_text' => $creds['post_text'],
'post_url' => $creds['post_url'],
'post_image' => $input['post_image'], // skip the "?? ''" part
'post_video' => $inputmp4['post_video'],
'post_gif' => $inputgif['post_gif'],
]);
Now, if either post_image, post_video or post_gif is empty, you'll get a error and can see if the data is wrong.
Also, on a kinda related note, did you know laravel has a good helper to save files in storage? Check it out

How to upload a file in Laravel?

Here is the code to upload an image to the database.
public function create(Request $request)
{
$this->validate($request, [
'comment' => 'required',
]);
$mess = new messageUser;
$mess->user_id = Auth::guard('userLogin')->user()->id;
$mess->message = $request->comment;
if($request->hasFile('image')){
$filenameWithExtention = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($filenameWithExtention,PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameStore = $fileName .'_'.time().'.'.$extension;
$path = $request->image->storeAs('images', $fileNameStore);
$mess->attach = $fileNameStore;
}
$mess->save();
return $mess;
}
Blade
<div class="form-group">
<textarea id="compose-textarea" name="comment"></textarea>
</div>
<div class="form-group">
<div class="input-group">
<input type="file" name="image" class="form-control inputFileVisible" placeholder="attach one file">
<button type="button" class="btn btn-fab btn-round btn-info"><i class="material-icons">attach an image</i>
</button>
</div>
</div>
<button type="submit" class="btn btn-primary"><i class="fa fa-envelope-o"></i>send image</button>
The code sends the message successfully but didn't upload the image.
You can do something like this:
if($request->hasFile('image')){
$filenameWithExtention = $request->file('image')->getClientOriginalName();
$fileName = pathinfo($filenameWithExtention,PATHINFO_FILENAME);
$extension = $request->file('image')->getClientOriginalExtension();
$fileNameStore = $fileName .'_'.time().'.'.$extension;
$path = $request->photo->storeAs('images', $fileNameStore);
$mess->attach = $fileNameStore;
}
For more Visit this
Thanks.
Note: Don't forget to run php artisan storage:link
What is the error show us please it will be better to guide you... BTW you ca use following code to uplaod an image/file
if ($request->image) {
$file = $request->File('image');
$ext = $student->username . "." . $file-
>clientExtension();
$file->storeAs('images/', $ext);
$student->image = $ext;
}

How to insert and update multiple selected values with codeigniter?

So I have a problem with many to many relationships.
Currently, I have surat and surat_user table.
How do I insert data into surat and at the same time insert multiple values from select2 multiple forms into surat_user table and how to get data so I can update it.
UPDATE :
I solve the insert problem please see answer below
But now i have no idea how to update those values.
For example
surat_user
id_surat | id_user
1 | 1
1 | 2
How to update surat_user (in controller and model) if i want to remove one of id_user where 'id_surat = 1`
At the moment i don't know how to fetch the multiple values into select2 form edit so here is mu uncomplete codes :
Controller
public function edit_sm($id_surat){
$this->load->view('template/header');
$this->load->view('template/sidebar');
$where = array('id_surat' => $id_surat);
//$data=array('id_status'=> $this->M_sm->get_option());
$data['surat'] = $this->M_sm->edit_sm($where,'surat')->result();
$this->load->view('v_edit_surat',$data);
$this->load->view('template/footer');
}
public function edit_sm_proses() {
$data = array(
'id_surat'=>$this->input->post('id_surat'),
'no_surat'=>$this->input->post('no_surat'),
'id_status'=>$this->input->post('id_status'),
'id_user'=>$this->input->post('id_user')
);
$where = array(
'id_surat' => $id_surat
);
$this->M_sm->edit_sm_proses($where,$data,'surat');
redirect('SuratMasuk');
}
Model:
public function edit_sm($where,$table){
$this->db->join('status_surat', 'status_surat.id_status = surat.id_status');
return $this->db->get_where($table,$where);
}
public function edit_sm_proses($where,$data,$table){
$this->db->where($where);
$this->db->update($table,$data);
}
View
<section class="content">
<div class="row">
<div class="col-xs-12">
<div class="box box-solid box-primary"">
<div class="box-header with-border">
<h3 class="box-title">Default Box Example</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<?php foreach ($surat as $key) { ?>
<form method="post" action="<?php echo base_url()."SuratMasuk/edit_sm_proses" ?>" enctype="multipart/form-data" />
<input type="hidden" name="id_surat" value="<?=$key->id_surat?>">
<div class="form-group">
<label class="control-label col-lg-2">No Surat</label>
<div class="col-lg-5">
<input type="text" name="no_surat" class="form-control no_surat" placeholder="Masukkan Nomor Surat" value="<?=$key->no_surat?>">
<span class="help-block"></span>
</div>
</div>
<br>
<br>
<div class="form-body">
<div class="form-group">
<label class="control-label col-lg-2">Status</label>
<div class="col-lg-5">
<select class="form-control select2 id_status" name="id_status" style="width: 100%;">
<option value="<?=$key->id_status;?>" selected="<?=$key->id_status;?>"><?php echo $key->status;?></option>
<?php foreach ($id_status as $row) { ?>
<option value="<?php echo $row->id_status; ?>"> <?php echo $row->status; ?></option>
<?php } ?>
</select>
<span class="help-block"></span>
</div>
</div>
</div>
<br>
<br>
<div class="form-body">
<div class="form-group">
<label class="control-label col-lg-2">Disposisi</label>
<div class="col-lg-5">
<select class="form-control select2 id_user" name="id_user[]" style="width: 100%;">
<option value="<?=$key->id_user;?>" selected="<?=$key->id_user;?>"><?php echo $key->nama;?></option>
<?php foreach ($id_user as $row) { ?>
<option value="<?php echo $row->id_user; ?>"> <?php echo $row->nama; ?></option>
<?php } ?>
</select>
<span class="help-block"></span>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-danger" type="reset" value="reset">Reset</button>
<button class="btn btn-info">Update</button><br>
Kembali
</form>
<?php
}
?>
</div>
<!-- box-footer -->
</div>
<!-- /.box -->
</div>
<!-- /.col -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
Current Result :
result from codes above
Manage to solve the problem by my self.
i change my controller to this:
public function add_sm_proses(){
$data = array(
'no_surat'=>$this->input->post('no_surat'),
'id_status'=>$this->input->post('id_status')
);
$insert = $this->M_sm->trans_surat_user($data);
if($insert=1){
redirect('SuratMasuk');
} else {
echo "<h2>Gagal menambahkan data</h2>";
}
}
change my model to this :
public function trans_surat_user($data){
$this->db->trans_start();
$this->db->insert('surat', $data);
$id_surat = $this->db->query('SELECT surat.id_surat FROM surat ORDER BY id_surat DESC limit 1');
foreach ($id_surat->result() as $row) {
$id_surat_result = $row->id_surat;
}
$id_user = $_POST['id_user'];
foreach ($id_user as $data2) {
array_push($id_user, $data2);
$this->db->query('INSERT INTO surat_user (id_surat,id_user) VALUES ('.$id_surat_result.','.$data2.')');
}
$this->db->trans_complete();
}
class SuratMasuk extends CI_Controller {
public function add_sm_proses(){
$data = array(
'no_surat'=>$this->input->post('no_surat'),
'id_status'=>$this->input->post('id_status'),
);
Select MAX ID from table like this
$id_surat = $this->db->query('SELECT MAX(surat.id_surat) AS maxid FROM surat')->row()->maxid;
Update:-
$id_surat will give MAX ID present in the table. Don't use for next record.
First, Increment it by value 1 and then use it
$id_surat = $id_surat + 1;
$id_user = $this->input->post('id_user') ? $this->input->post('id_user') : array();
First, check if $id_user have values or not otherwise foreach loop will give e error
if(count($id_user) > 0){
foreach ($id_user as $u){
$data_values = array('id_surat' => $id_surat, 'id_user' => $u);
$this->db->insert('surat_user', $data_values);
}
}
$insert = $this->M_sm->add_sm($data);
$insert will not always return 1. So, only check if value exists
if($insert){
redirect('SuratMasuk');
} else {
echo "<h2>Gagal menambahkan data</h2>";
}
}
}
First, Show all record from DB and for each record add a button to edit the record.
Note:- Don't use <form> inside the loop
<a class="btn btn-warning btn-sm" href="<?= base_url('SuratMasuk/edit_sm/'.$row->id_surat)?>"><i class="fa fa-pencil-square-o" aria-hidden="true"></i>Edit</a>
Controller for Edit
I'm just adding backend code here
where and table is reserved word for DB. It is better to not use it or use in another way.
public function edit_sm($id_surat){
$condition_array = array('id_surat' => $id_surat);
$data['surat'] = $this->M_sm->edit_sm($condition_array ,'surat');
}
Model for Edit
Get the record for edit
This function is getting only one record from DB so use row()
public function edit_sm($condition_array ,$record_in){
$this->db->join('status_surat', 'status_surat.id_status = surat.id_status');
return $this->db->get_where($record_in, $condition_array )->row();
}
Now, Form for will show with data populated in it.
Getting updated data from Controller
public function edit_sm_proses() {
$data = array(
'id_surat'=> $this->input->post('id_surat'),
'no_surat'=>$this->input->post('no_surat'),
'id_status'=>$this->input->post('id_status'),
'id_user'=>$this->input->post('id_user')
);
$condition_array = array(
'id_surat' => $this->input->post('id_surat')
);
$this->M_sm->edit_sm_proses($condition_array, $data, 'surat');
redirect('SuratMasuk');
}
Updating data in Model
public function edit_sm_proses($condition_array, $data, $record_in){
$this->db->where($condition_array);
return $this->db->update($record_in, $data);
}