Looping data in controller from model codeigniter - php

I'm trying to prevent the user to create the same username. well my real problem is how to loop a list of data from model in controller. Maybe we know how to loop it in view by using this -> data['user'] and in view we can call $user. but how can we do that in controller layer.
here's my code
Controller
$username = strtolower($this->input->post('name'));
$fixUsername = str_replace(" ",".",$username);
$counter = 1;
$list[] = $this->addusermodel->getAllUsername();
for($i=0;$i<sizeof($list);$i++) {
if($list[$i] == $fixUsername) {
$counter = 0;
}
}
if($counter == 0) {
$data['result'] = "The username has already been taken";
$this->load->view('adduserview',$data);
} else {
$data = array(
'Nama' => $this->input->post('name'),
'Username' => $fixUsername."#praba",
'Password' => md5($this->input->post('password')),
'created' => date("Y-m-d h:i:sa"),
'createdBy' => $createdBy,
'lastModified' => date("Y-m-d h:i:sa"),
'lastModifiedBy' => $lastModifiedBy
);
$this->addusermodel->saveUser($data);
//$data['Username'] = $listName;
$data['message'] = "New user successfully added.";
$data['messageContent'] = "The username: ".$fixUsername."#praba". $counter;
$this->load->view('successpageview',$data);
//redirect('successpageview','refresh');
}
my model (is like usual)
function getAllUsername() {
$this->db->select('Username');
$this->db->from('tbluser');
$query = $this->db->get();
return $query->result_array();
}

I think a better approach would be to create another function in your model, which searches your database by ID, or by email, or by another unique field. If the function returns a row - then the user exists. If it returns nothing - then add a new user.

Related

Insert Batch php mysql with check duplicate and sum values of field duplicate

i have 1 million data using foreach.
ex table:
table
the data
data
i want to inserting that's data using batch/multipleinsert, but i have problem when i got duplicate data. if data duplicate i want the field amount will sum and update amount field with sum amount duplicated data.
this is my code before
<?php
foreach ($data_transaksi as $key)
{
if($key['STATUS_COA'] != $key['CHART_OF_ACCOUNT_STATUS'])
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2);
}
else
{
$amount = round($key['AMOUNT'],2) *-1;
}
}
else
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2)*-1;
}
else
{
$amount = round($key['AMOUNT'],2);
}
}
$dt_exsis = $this->ledger_model->cek_data_coa_exsis($key['COA_CODE'],$modul,$ID_USER);
if(empty($dt_exsis['id']))
{
//TRYINSERTINGBATCH
// $datainsert[] = '('.$key['COA_CODE'].','.$amount.','.$ID_USER.',"'.$modul.'")';
// $test = $key['COA_CODE'];
$datainput = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
$this->ledger_model->save_rows_to_table($datainput,'finance_lapkue_temp');
}
else
{
$amount_fix = $amount + $dt_exsis['AMOUNT'];
$data=array(
'AMOUNT' => $amount_fix
);
$this->ledger_model->edit_rows_to_table_where($data,'finance_lapkue_temp','id',$dt_exsis['id']);
// $q = "UPDATE finance_lapkue_temp set AMOUNT = '$amount_fix' where id = '".$dt_exsis['id']."'";
// $this->db->query($q);
}
// $data_amount[$key['COA_CODE']] += $amount;
}
?>
if i using this code, the proccess so slow
Good option will to pass only data to DB that you want to insert. All the data cleaning task can be done in controller.
// Create a data array and add all info
$data = [];
//if user does not exist add it in array
if (empty($dt_exist($id))) {
$data[$ID_USER] = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
}
else {
//if user exist in $data just modify the amount
if (!empty($data[$ID_USER])) {
$data[$ID_USER]['AMOUNT'] += $dt_exsis['AMOUNT'];
}
else {
// if user does not exist in data create add all info
$data[$dt_exsis['ID_USER']] = array(
'COA_CODE' => $dt_exsis['COA_CODE'],
'AMOUNT' => $dt_exsis['amount'],
'MODUL' => $dt_exsis['modul'],
'USER_ID' => $dt_exsis['ID_USER']
);
}
}
This will save multiple calls to DB and at the end you can pass $data and do multiple insert.

data getting inserted twice in database - Codeigniter

So I've spent hours on trying to fix this one. every time I upload a file. all the data/id3 tags are being inserted twice on my database. before it was working properly now it has this bug and I badly need some help now.
In my controller I am executing update at the same time since I want also to update the data inserted into database with the details from the id3 tags.
Controller
public function save()
{
$id = $this->session->userdata('user_id');
$status = $this->input->post('status');
$original_file = $this->input->post('original_file');
$revised_file = $this->input->post('revised_file');
$song_data = array(
'user_id' => $id,
'song_info_status' => $status,
'song_info_file_name' => $original_file,
'song_info_revised_file_name' => $revised_file,
'song_info_date_added' => 'now()',
'song_info_date_updated' => 'now()'
);
$song_info_id = $this->song_info_model->save($song_data);
$composer_data = array(
'composer_name' => ''
);
$composer_id = $this->composer_model->save($composer_data);
$song_composer_data = array(
'song_info_id' => $song_info_id,
'composer_id' => $composer_id
);
$this->song_composer_model->save($song_composer_data);
$status_data = array(
'song_info_id' => $song_info_id
);
$status_id = $this->status_model->save($status_data);
$tags_info = array();
$tags_info = $this->getTagsInfo(FCPATH ."temp" . "/" .$revised_file);
if(isset($tags_info['Author']))
{
// echo iconv("UTF-8","EUC-JP", $tags_info['Author']);
//echo $str = mb_convert_encoding($tags_info['Author'], "UTF-8", "auto");
$status_data = array(
'status_artist_name' => $tags_info['Author']
);
$this->status_model->update($status_data, $status_id);
}
if(isset($tags_info['Title']))
{
$song_data = array(
'song_info_original_title' => $tags_info['Title']
);
$this->song_info_model->update($song_data, $song_info_id);
}
rename($this->source.$revised_file, $this->destination.$revised_file);
}
In my model I am just getting the data I have from my controller. there's no loop or anything and I really can't find the culprit.
Model
public function save($data)
{
$this->db->insert('song_info', $data);
return $this->db->insert_id();
}
public function update($data, $id)
{
$this->db->where('song_info_id', $id);
$this->db->update('song_info', $data);
}

save all associated records at once

I am able to save associated records in cakephp3 but if you look at the code , the records are not saved all at once with 1 save call.
I did have a problem trying to save all the records at once. If you look at how its done you see the Guardian and Users table are save separately.
The code works and saves the records but saving all at once in 1 save call has been an issue as I got an error on the guardian table.
Guardians have a 1 to many relationship with students
Students and Users have a 1 to 1
Students to subjects and availabilityFotStudents both have a many to many
Code
public function add($gId=0) {
$this->loadModel("Guardians");
$this->loadModel('PaymentTypes');
$this->set("title","Add Student");
$guardians=null;
if ($gId>0){
$guardians =$this->Guardians->get($gId);
}
if ($this->request->is('post')) {
if ( $this->request->data['studenttype']==0){ //enquiry
$this->request->data['students']['address_billing'] = 0;
$this->request->data['students']['student_enq'] = 1;
}
else if ( $this->request->data['studenttype']==1){ //waitlist
$this->request->data['students']['address_billing'] = 1;
$this->request->data['students']['student_enq'] = 0;
}
else if ( $this->request->data['studenttype']==2){ //skip waitlist
$this->request->data['students']['address_billing'] = 4;
$this->request->data['students']['student_enq'] = 0;
}
if ( $this->request->data['students']['tutoring_typest_id']==1){
$this->request->data['students']['group_status']=0;
}
else if ( $this->request->data['students']['tutoring_typest_id']>1){
$this->request->data['students']['group_status']=1;
}
if ($this->request->data['students']['tutoring_typest_id']==3 ){//group only
$this->request->data['students']['address_billing'] = 4;
}
$data = $this->request->data;
// debug($data);
$uname= $this->request->data['Users']['username'];
if ($this->Students->Users->findByUsername($uname)->count()) {
$this->Flash->error(__('Username exists. Please, try again.'));
return $this->redirect(["action"=>"add",$gId]);
}
$userId=0;
$entity = $this->Students->Users->newEntity($this->request->data['Users'],['validate'=>false]);
$entity->role = "student";
$entity['role_id'] = 4;
$entity = $this->Students->Users->save($entity);
// debug( $entity);
$studentUserId = $entity->id;
if($guardians==null) {
$guardians = $this->Guardians->newEntity($this->request->data['guardians'], ['validate' => false]);
}
$guardianEntity = $this->Guardians->save($guardians);
$guardians = $this->Students->newEntity();
$studentData = $this->request->data['students'];
$studentData['subjects'] = $this->request->data['subjects'];
$studentData['availability_for_students'] = $this->request->data['availability_for_students'];
$studentEntity = $this->Students->patchEntity($guardians,$studentData,
[
"validate"=>false,
'associated' => [
"AvailabilityForStudents"=>["validate"=>false],
"Subjects"=>["validate"=>false]
]
]
);
$studentEntity->guardian_id = $guardianEntity->id;
$studentEntity->user_id = $studentUserId;
$studentEntity = $this->Students->save($studentEntity,
[
"validate"=>false,
'associated' => [
"AvailabilityForStudents"=>["validate"=>false],
"Subjects"=>["validate"=>false]
]
]
);
if ($studentEntity) {
$this->Flash->success(__('The student has been saved'));
return $this->redirect(["action"=>"index2"]);
} else {
$this->Flash->error(__('The student could not be saved. Please, try again.'),'flash_alert');
}
}//post
$subjects = $this->Students->Subjects->find('list', array( 'order' => array('Subjects.name' => 'asc') ));
$weekdays = $this->Students->weekDays;
$tutoringTypes = $this->Students->TutoringTypeStudents->find('list');
//$payments = $this->Student->paymentOptions;
$this->PaymentTypes->primaryKey("name");
$payments = $this->PaymentTypes->find( 'list', array(
'fields' => array('PaymentTypes.name','PaymentTypes.name')) );
$referrals = $this->Students->Referrals->find('list');
$tutorGender = $this->Students->Lessons->Tutors->tutorGender;
$this->set('guardians', $guardians);
$this->set(compact('referrals','subjects', 'tutoringTypes', 'weekdays','payments','tutorGender'));
}
you can use Tranactional data save. Where you can run multiple save method. if any save method failed then no data will be save. so it works like "1 save call" which you mentioned

about laravel form calculation

I had encountered the calculation in Laravel or maybe PHP stuff, I would like to ask for solution or maybe some others approach to get the things done.
These are the codes in the Model
public function getRedeemCount($member_id){
$count = DB::table('stamps')->where('user_id', '=', $member_id)->select('stamp_counter')->first();
return $count;
}
public function getFreeOfferCount($member_id){
$free_offer_count = DB::table('stamps')->where('user_id', '=', $member_id)->select('free_offer_counter')->first();
return $free_offer_count;
}
These are the codes in the Controller
public function redeemFreeOffer(Request $request)
{
$free_offer_counter = $request->input('minus_free_offer_counter');
$member_id = $request->input('sub_id');
$total_stamp_count = $this->userModel->getRedeemCount($member_id);
$free_offer_count = $this->userModel->getFreeOfferCount($member_id);
if(!$free_offer_count){
$insert_arr = array(
'user_id' => $member_id,
'free_offer_counter' => $free_offer_counter,
'created_at'=>date("Y-m-d H:i:s")
);
$stamps = DB::table('stamps')->insert($insert_arr);
if($stamps){
$arr = array('status' => 1,'message'=>'success','value'=>$free_offer_counter);
}
}
else {
$total_stamp_count->stamp_counter;
$total_free_offer_count = floor($total_stamp_count->stamp_counter/10);
$current_offer_count = $free_offer_count->free_offer_counter - $free_offer_counter;
$update_arr = array(
'free_offer_counter' => $current_offer_count,
'updated_at' => date("Y-m-d H:i:s")
);
$stamps = DB::table('stamps')->where('user_id', $member_id)->update($update_arr);
if ($stamps) {
$arr = array('status' => 1, 'message' => 'success', 'value' => $current_offer_count);
}
}
echo json_encode($arr);
}
Since I am using jQuery AJAX, so there's too much code, but I think it should be enough information for now. If it is insufficient, I will provide more in future.
The problem is how do I inject $total_free_offer_count into $current_offer_count? I do not have any columns that stored $total_free_offer_count.
$total_stamp_count->stamp_counter;
$total_free_offer_count = floor($total_stamp_count->stamp_counter/10);
$current_offer_count = $free_offer_count->free_offer_counter - $free_offer_counter;

Cant pass array value from codeigniter controller to view

Inside my controller, I have a line that needs to pass $content['pass_check'] to the view. It is inside an if statement that checks for validation. This I have found causes it to break. Once I move the $content['pass_check'] outside of any if statement, it works just fine passing to the view. All of the other values are passed (accounts, expense_accounts, vendors, terms). What must I do to get it to pass within this if statement. I've even tried moving it outside of the validation and it still wont set.
function create() {
require_permission("INVOICE_EDIT");
$this->load->library("form_validation");
$this->form_validation->set_rules("invoice_number", "Invoice Number", "required");
if($this->form_validation->run() !== false) {
$post = $this->input->post();
$this->session->set_userdata("create_invoice_vendor", $post['vendor_id']);
$this->session->set_userdata("create_invoice_date", $post['invoice_date']);
$invoice_number_exists = $this->invoices->count(array("invoice_number" => $post['invoice_number'])) > 0;
$post['invoice_date'] = date("Y-m-d", strtotime($post['invoice_date']));
$post['due_date'] = date("Y-m-d", strtotime($post['due_date']));
$post['date_entered'] = "now()";
$id = $this->invoices->insert_invoice($post);
$this->load->model("vendors");
if(isset($post['invoice_number'])){
$string_check= $post['invoice_number'];
$string_check= preg_replace('/\d/', '#', $string_check);
$string_check= preg_replace('/\w/', '#', $string_check);
$invoice_pattern=array();
$invoice_pattern = $this->db->select("invoice_pattern")->where("vendor_id",
$post['vendor_id'])->get("vendors")->result();
$invoice_pattern=$invoice_pattern[0]->invoice_pattern;
* //// THIS IS WHERE I NEED HELP ///////
if($invoice_pattern == $string_check){
***$content['post_check'] = 1;***
$this->invoices->flag_invoice($id);
};
};
$history = array(
"type" => "invoice_entered",
"comments" => "Invoice was entered",
"link" => $id,
"admin_id" => $this->user->admin_id,
"date" => "now()",
);
$this->vendors->insert_history($post['vendor_id'], $history);
if($post['flagged'] == 1) {
$this->invoices->flag_invoice($id);
}
if($invoice_number_exists) {
redirect("invoices/confirm_invoice/".$id);
} else {
// redirect("invoices/view/".$id);
redirect("invoices/create");
}
}
$content['accounts'] = $this->db->get("acct_chart_of_accounts")->result();
$content['expense_accounts'] = $this->db->get("invoice_expense_accounts")->result();
$content['vendors'] = $this->db->select("vendor_id, name, terms, override, invoice_pattern")
->order_by("name ASC")->get("vendors")->result();
$content['terms'] = $this->db->query("SELECT DISTINCT(terms) FROM vendors")->result();
}
}
$this->template['sub_heading'] = "Create";
$this->template['content'] = $this->load->view("invoices/create", $content, true);
$this->template['sidebar'] = $this->load->view("invoices/sidebar", array(), true);
$this->template['scripts'] = array("codeigniter/javascript/invoices/create.js");
$this->template['styles'][] = "codeigniter/styles/invoices/create.css";
$this->display();
}
Obviously it won't pass it to the view if the condition doesn't match, because you're only declaring the variable within the condition if it matches.
Just create $content['pass_check'] with an initial value of 0 or whatever before the conditional check first.
function create() {
...snip...
$content['pass_check'] = 0;
if($invoice_pattern == $string_check) {
$content['post_check'] = 1;
$this->invoices->flag_invoice($id);
};
...snip...
}
Let me know if this works or not please.

Categories