I am a beginner for Codeigniter. I'm currently creating a registration page. I want to enter data into 4 tables at once using CodeIgniter. the table is tbl_asesi, tbl_pdd_non_formal, tbl_work, tbl_organization, but new data comes in 1 table, namely tbl_asesi while the other tables are still empty. can you help me fix the code?
The controller that I use is as follows
my controller :
<?PHP
defined('BASEPATH') OR exit('No direct script access allowed');
class Pendaftaran extends CI_Controller {
public function index()
{
$data = array(
'bidang' => $this->m_pendaftaran->get_bidang(),
'subbidang' => $this->m_pendaftaran->get_subbidang(),
'jenis_bidang' => $this->m_pendaftaran->get_jenis_bidang(),
'level' => $this->m_pendaftaran->get_level(),
'okupasi' => $this->m_pendaftaran->get_okupasi(),
'unitinti' => $this->m_pendaftaran->get_unitinti(),
'unitpilihan1' => $this->m_pendaftaran->get_unitpilihan1(),
'unitpilihan2' => $this->m_pendaftaran->get_unitpilihan2(),
'unitpilihan3' => $this->m_pendaftaran->get_unitpilihan3(),
'bidang_selected' => '',
'subbidang_selected' => '',
'jenis_bidang_selected' => '',
'level_selected' => '',
'okupasi_selected' => '',
'unitinti_selected' => '',
'unitpilihan1_selected' => '',
'unitpilihan2_selected' => '',
'unitpilihan3_selected' => '',
);
$this->template->load('static','pendaftaran',$data);
}
function __construct(){
parent::__construct();
$this->load->library(array('form_validation'));
$this->load->model('m_pendaftaran');
$this->load->helper(array('form', 'url'));
}
public function daftarasesi() {
$this->form_validation->set_rules('nama', 'NAMA','required');
$this->form_validation->set_rules('nik', 'NIK','required');
$this->form_validation->set_rules('jenis_kelamin', 'JENIS_KELAMIN','required');
$this->form_validation->set_rules('alamat', 'ALAMAT','required');
$this->form_validation->set_rules('jabatan', 'JABATAN','');
$this->form_validation->set_rules('asal_institusi', 'ASAL_INSTITUSI','required');
$this->form_validation->set_rules('alamat_institusi', 'ALAMAT_INSTITUSI','required');
$this->form_validation->set_rules('no_hp', 'NO_HP','required');
$this->form_validation->set_rules('email','EMAIL','required|valid_email');
$this->form_validation->set_rules('sd', 'SD','required');
$this->form_validation->set_rules('kota_sd', 'KOTA_SD','required');
$this->form_validation->set_rules('tahun_sd', 'TAHUN_SD','required');
$this->form_validation->set_rules('smp', 'SMP','required');
$this->form_validation->set_rules('kota_smp', 'KOTA_SMP','required');
$this->form_validation->set_rules('tahun_smp', 'TAHUN_SMP','required');
$this->form_validation->set_rules('sma', 'SMA','required');
$this->form_validation->set_rules('kota_sma', 'KOTA_SMA','required');
$this->form_validation->set_rules('tahun_sma', 'TAHUN_SMA','required');
$this->form_validation->set_rules('d', 'D');
$this->form_validation->set_rules('kota_d', 'KOTA_D');
$this->form_validation->set_rules('tahun_d', 'TAHUN_D');
$this->form_validation->set_rules('s1', 'S1');
$this->form_validation->set_rules('kota_s1', 'KOTA_S1');
$this->form_validation->set_rules('tahun_s1', 'TAHUN_S1');
$this->form_validation->set_rules('s2', 'S2');
$this->form_validation->set_rules('kota_s2', 'KOTA_S2');
$this->form_validation->set_rules('tahun_s2', 'TAHUN_S2');
$this->form_validation->set_rules('s3', 'S3');
$this->form_validation->set_rules('kota_s3', 'KOTA_S3');
$this->form_validation->set_rules('tahun_s3', 'TAHUN_S3');
$this->form_validation->set_rules('pelatihan', 'PELATIHAN');
$this->form_validation->set_rules('lembaga', 'LEMBAGA');
$this->form_validation->set_rules('kota_pelatihan', 'KOTA_PELATIHAN');
$this->form_validation->set_rules('tahun_pelatihan', 'TAHUN_PELATIHAN');
$this->form_validation->set_rules('kegiatan', 'KEGIATAN');
$this->form_validation->set_rules('institusi', 'INSTITUSI');
$this->form_validation->set_rules('tahun_kerja', 'TAHUN_KERJA');
$this->form_validation->set_rules('nama_organisasi', 'NAMA ORGANISASI');
$this->form_validation->set_rules('status_anggota', 'STATUS ANGGOTA');
$this->form_validation->set_rules('surat_organisasi', 'SURAT ORGANISASI');
$this->form_validation->set_rules('tahun_organisasi', 'TAHUN_ORGANISASI');
$this->form_validation->set_rules('bidang', 'BIDANG','required');
$this->form_validation->set_rules('subbidang', 'SUBBIDANG','required');
$this->form_validation->set_rules('level', 'LEVEL','required');
$this->form_validation->set_rules('jenis_bidang', 'JENIS_BIDANG','required');
$this->form_validation->set_rules('okupasi', 'OKUPASI','required');
$this->form_validation->set_rules('unitinti', 'UNITINTI','required');
$this->form_validation->set_rules('unitpilihan1', 'UNITPILIHAN1','required');
$this->form_validation->set_rules('unitpilihan2', 'UNITPILIHAN2','');
$this->form_validation->set_rules('unitpilihan3', 'UNITPILIHAN3','');
if($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('gagaldaftar', 'Maaf, Pendaftaran Gagal Dilakukan.');
$this->template->load('static','pendaftaran');
}else{
$data_asesi['nama'] = $this->input->post('nama');
$data_asesi['nik'] = $this->input->post('nik');
$data_asesi['jenis_kelamin'] = $this->input->post('jenis_kelamin');
$data_asesi['alamat'] = $this->input->post('alamat');
$data_asesi['jabatan'] = $this->input->post('jabatan');
$data_asesi['asal_institusi'] = $this->input->post('asal_institusi');
$data_asesi['alamat_institusi'] = $this->input->post('alamat_institusi');
$data_asesi['no_hp'] = $this->input->post('no_hp');
$data_asesi['email'] = $this->input->post('email');
$data_asesi['sd'] = $this->input->post('sd');
$data_asesi['kota_sd'] = $this->input->post('kota_sd');
$data_asesi['tahun_sd'] = $this->input->post('tahun_sd');
$data_asesi['smp'] = $this->input->post('smp');
$data_asesi['kota_smp'] = $this->input->post('kota_smp');
$data_asesi['tahun_smp'] = $this->input->post('tahun_smp');
$data_asesi['sma'] = $this->input->post('sma');
$data_asesi['kota_sma'] = $this->input->post('kota_sma');
$data_asesi['tahun_sma'] = $this->input->post('tahun_sma');
$data_asesi['d'] = $this->input->post('d');
$data_asesi['kota_d'] = $this->input->post('kota_d');
$data_asesi['tahun_d'] = $this->input->post('tahun_d');
$data_asesi['s1'] = $this->input->post('s1');
$data_asesi['kota_s1'] = $this->input->post('kota_s1');
$data_asesi['tahun_s1'] = $this->input->post('tahun_s1');
$data_asesi['s2'] = $this->input->post('s2');
$data_asesi['kota_s2'] = $this->input->post('kota_s2');
$data_asesi['tahun_s2'] = $this->input->post('tahun_s2');
$data_asesi['s3'] = $this->input->post('s3');
$data_asesi['kota_s3'] = $this->input->post('kota_s3');
$data_asesi['tahun_s3'] = $this->input->post('tahun_s3');
//tabel tbl_pdd_non_formal
$data_non_formal = array();
$data_non_formal['pelatihan'] = $this->input->post('pelatihan');
$data_non_formal['lembaga'] = $this->input->post('lembaga');
$data_non_formal['kota_pelatihan'] = $this->input->post('kota_pelatihan');
$data_non_formal['tahun_pelatihan'] = $this->input->post('tahun_pelatihan');
//tabel tbl_pekerjaan
$data_pekerjaan = array();
$data_pekerjaan['kegiatan'] = $this->input->post('kegiatan');
$data_pekerjaan['institusi'] = $this->input->post('institusi');
$data_pekerjaan['surat_pendukung'] = $this->input->post('surat_pendukung');
$data_pekerjaan['tahun_kerja'] = $this->input->post('tahun_kerja');
//tbl_organisasi
$data_organisasi = array();
$data_organisasi['nama_organisasi'] = $this->input->post('nama_organisasi');
$data_organisasi['status_anggota'] = $this->input->post('status_anggota');
$data_organisasi['surat_organisasi'] = $this->input->post('surat_organisasi');
$data_organisasi['tahun_organisasi'] = $this->input->post('tahun_organisasi');
//tbl_asesi
$data_asesi['bidang'] = $this->input->post('bidang');
$data_asesi['subbidang'] = $this->input->post('subbidang');
$data_asesi['level'] = $this->input->post('level');
$data_asesi['jenis_bidang'] = $this->input->post('jenis_bidang');
$data_asesi['okupasi'] = $this->input->post('okupasi');
$data_asesi['unitinti'] = $this->input->post('unitinti');
$data_asesi['unitpilihan1'] = $this->input->post('unitpilihan1');
$data_asesi['unitpilihan2'] = $this->input->post('unitpilihan2');
$data_asesi['unitpilihan3'] = $this->input->post('unitpilihan3');
// var_dump($data_asesi);
// var_dump($data_non_formal);
// var_dump($data_pekerjaan);
// var_dump($data_organisasi);
$this->m_pendaftaran->daftarasesi($data_asesi, $data_non_formal, $data_pekerjaan, $data_organisasi);
// $this->m_pendaftaran->daftarasesi($data);
$this->session->set_flashdata('berhasil', 'Pendaftaran Berhasil Dilakukan.');
$this->template->load('static','pendaftaran');
}
}
public function lakukan_download_asesi(){
force_download('berkas/berkas_asesi.rar',NULL);
}
}
the model that I use is as follows
my model :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class M_pendaftaran extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function daftarasesi($asesi, $non_formal, $pekerjaan, $organisasi)
{
// insert data asesi //
$this->db->insert('tbl_asesi',$asesi);
$nik_fk = $this->db->insert_nik();
// insert data non formal //
$data_non_formal['nik_fk'] = $nik_fk;
$this->db->insert('tbl_pdd_non_formal',$non_formal);
return $insert_nik = $this->db->insert_nik();
// insert data pekerjaan //
$data_pekerjaan['nik_fk'] = $nik_fk;
$this->db->insert('tbl_pekerjaan',$pekerjaan);
return $insert_nik = $this->db->insert_nik();
// insert data organisasi //
$data_organisasi['nik_fk'] = $nik_fk;
$this->db->insert('tbl_organisasi',$organisasi);
return $insert_nik = $this->db->insert_nik();
}
I think you're doing wrong and in Codeigniter there is no query builder function exists called $this->db->insert_nik() and you were returning this, so it was not working. So you shouldn't use this.
You can insert data into multiple tables from one form as following way and Use this in your model.
public function daftarasesi($asesi, $non_formal, $pekerjaan, $organisasi)
{
$this->db->trans_start();
// insert data asesi //
$this->db->insert('tbl_asesi',$asesi);
// insert data non formal //
$this->db->insert('tbl_pdd_non_formal',$non_formal);
// insert data pekerjaan //
$this->db->insert('tbl_pekerjaan',$pekerjaan);
// insert data pekerjaan //
$this->db->insert('tbl_pekerjaan',$pekerjaan);
// insert data organisasi //
$this->db->insert('tbl_organisasi',$organisasi);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
return FALSE;
} else {
$this->db->trans_commit();
return TRUE;
}
}
You can run as many queries as you want between the start/complete
functions and they will all be committed or rolled back based on
success or failure of any given query.
N.B: Always use transaction when you're dealing with multiple insertion/updation.
Related
Hello everyone I'm getting confused because when I'm running a code with some condition only 1 column getting updated and the others column stay null, I'm sure there is no typo with the column name in table nor in code here is my code :
public function solusi_line($id)
{
$idasli = base64_decode($id);
$solusi = solusi::where('request_id', $idasli)->orderBy('created_at', 'asc')->get();
$count = solusi::where('request_id', $idasli)->orderBy('created_at', 'desc')->count();
$cekakun = Session::get('id');
$adminkah = Admin::where('user_id', $cekakun)->count();
// dd($solusi);
//jika admin ke bagian sini
if ($adminkah != 0) {
# code...
return view('admin.detail_feedback', compact('solusi', 'count'));
} else {
return view('user.detailfeedback_user', compact('solusi', 'count'));
}
//klo user kebagian user
}
public function FirstFeedback($id)
{
$datas = Kirim::where('id', $id)->first();
return view('admin.detailprogress', compact('datas'));
}
//solusi dari admin
public function solusiPost(Request $request)
{
$itungsolusi = solusi::where('request_id', $request->idRequest)->count();
$data = new solusi();
$data->request_id = $request->idRequest;
$data->pengirim_id = Session::get('id');
$data->penerima_id = $request->idPenerima;
$data->solusi = $request->solusi;
$file = $request->file('lampiran_solusi');
if (!empty($file)) {
$ext = $file->getClientOriginalExtension();
$name = time() . '.' . $ext;
$file->move('upload/lampiran/', $name);
$data->lampiran = $name;
$data->url_lampiran = url('upload/lampiran') . "/" . $name;
} else {
$data->lampiran = null;
$data->url_lampiran = null;
}
if ($data->save()) {
//matiin sementara
$check = DB::table('kirims')->where('id', $data->request_id)->first();
$user = Kirim::find($check->id);
// dd($user);
if (!is_null($user)) {
// $user->update(['status' => 'CheckByUser', 'status_feedback' => 'Ya']);
$user->update(['remarks' => 'Ya', 'status' => 'CheckByUser', 'status_feedback' => 'Ya']);
}
//just status column is success to update but not the remarks and status_feedback column
$id_solusi = $data->id;
$thisUser = DB::table('kirims')
->join('simpan_users', 'kirims.pengirim_id', '=', 'simpan_users.user_id')
->join('solusis', 'kirims.id', '=', 'solusis.request_id')
->where('kirims.id', $data->request_id)
->where('solusis.id', $id_solusi)
->select('kirims.email', 'kirims.ticket_id', 'solusis.solusi', 'solusis.lampiran', 'solusis.url_lampiran')
->first();
// dd($thisUser);
here the problem
$check = DB::table('kirims')->where('id', $data->request_id)->first();
$user = Kirim::find($check->id);
// dd($user);
if (!is_null($user)) {
// $user->update(['status' => 'CheckByUser', 'status_feedback' => 'Ya']);
$user->update(['remarks' => 'Ya', 'status' => 'CheckByUser', 'status_feedback' => 'Ya']);
}
//just status column is success to update but not the remarks and status_feedback column
I really appreciate for any help, I getting stuck because laravel not showing error too, thank you.
You should check your Kirim model, where you need to define $fillable property. Something like below.
class Kirim extends Model {
protected $fillable = ['remarks', 'status', 'status_feedback',''];
// All fields inside $fillable array can be mass-assigned
}
use update statement like this.
$user->remarks = 'Ya',
$user->status = 'CheckByUser',
$user->status_feedback = 'Ya'
$user->update();
few days ago i faced the same issue and fixed it as i told you .
i want to create a condition which a user would choose whether he wants to use an input which means a database would create an auto_incremented id or he wants to use an older data which will not use new id but only use it. i have used dropdown database populate for my old input.
My Dropdown list
//get contractor list
$Contractor_List = $this->foo_pro->get_list_contractors();
$opt = array('' => '');
foreach ($Contractor_List as $Contractor_No) {
$opt[$Contractor_No] = $Contractor_No;
}
$data['con_list'] = form_dropdown('',$opt,'','ProjectID = "Contractor_No" name="contractorNo" id="" class="w3-select w3-border w3-hover-light-grey"');
My Controller
public function save_createdProject()
{
$data_project = array();
$data_contractor = array();
//project data
if ($this->input->post('year') === '') {
$data_project['P_Year'] = 15;
}else{
$data_project['P_Year'] = $this->input->post('year');
}
if ($this->input->post('code') === '') {
$data_project['Code'] = 'KO';
}else{
$data_project['Code'] = $this->input->post('code');
}
$data_project['ProjectID'] = $this->input->post('project');
$data_project['Contract_Amount'] = $this->input->post('camount');
//contractor data
if ($this->input->post('cname') === '' && $this->input->post('caddress') === '') {
$data_project['Contractor_No'] = $this->input->post('contractorNo');
}else{
$data_contractor['Contractor_Name'] = $this->input->post('cname');
$data_contractor['Contractor_Address'] = $this->input->post('caddress');
}
$this->foo_pro->add_project($data_project, $data_contractor);
redirect('Main/project','refresh');
//var_dump($data);exit;
}
My Model
public function add_project($data_project, $data_contractor)
{
//contractor
$this->db->insert('contractor', $data_contractor);
$Contractor_No = $this->db->insert_id();
//project
$data_project['Contractor_No'] = $Contractor_No;
$this->db->insert('project', $data_project);
$ProjectID = $this->db->insert_id();
}
this here is my problem except inserting the older data which is the contractor_no 1 it creates another data that would insert as contractor_no 4.. but also i need to insert new data for new contractor_name..
I'm struggling to update an existing record through an Eloquent Model in Laravel 5.4
I have for creating a record that works perfectly fine, I took it and modified it to try and update the record:
public function commitEdit ($char_edit_id)
{
$edited_character = \DB::table('characters')->where('char_id', $char_edit_id)->first();
$edited_character->campaign_id = 1;
$edited_character->character_name = request('characterName');
$edited_character->Race = request('race');
$edited_character->Sub_Race = request('subRaceField');
$edited_character->Class = request('class');
$edited_character->Level = request('level');
$edited_character->Strength = request('strength');
$edited_character->Dexterity = request('dexterity');
$edited_character->Constitution = request('constitution');
$edited_character->Intelligence = request('intelligence');
$edited_character->Wisdom = request('wisdom');
$edited_character->Charisma = request('charisma');
$levelVar = request('level');
if ($levelVar >= 4) {
$edited_character->Proficiency = 2;
} else if ($levelVar >= 8) {
$edited_character->Proficiency = 3;
}
$edited_character->Trained_Skills = request('skillsField');
$edited_character->Languages = request('languagesField');
$edited_character->Hit_Die = 1;
$edited_character->max_HP = request('max-hp');
$edited_character->Alignment = request('alignment');
$edited_character->Armor_Class = request('armor-class');
$edited_character->Initiative = request('initiative');
$edited_character->Speed = request('speed');
$edited_character->Background = request('background');
$edited_character->update();
return redirect('./characters');
That gives this error:
Call to undefined method stdClass::update()
I have tried using save() but I get the same error with save() instead of update()
Thanks in advance c:
Documentation
If you just need to retrieve a single row from the database table, you may use the first method. This method will return a single StdClass object:
$edited_character is a stdClass, no Eloquent model.
You can try this code:
public function commitEdit ($char_edit_id)
{
$edited_character = \DB::table('characters')->where('char_id', $char_edit_id)->update([
'campaign_id' => 1,
'character_name' => request('characterName'),
'Race' => request('race'),
//others property
]);
}
Or create Characters model which will be extends from Illuminate\Database\Eloquent\Model and use save method:
public function commitEdit ($char_edit_id)
{
$edited_character = Characters::where('char_id', $char_edit_id)-first();
//your code with properties
$edited_character->save();
}
You can try this way:
public function commitEdit ($char_edit_id)
{
$edited_character = Characters::find($char_edit_id);
$edited_character->character_name = request('characterName');
$edited_character->Race = request('race');
$edited_character->Sub_Race = request('subRaceField');
$edited_character->Class = request('class');
$edited_character->Level = request('level');
$edited_character->Strength = request('strength');
$edited_character->Dexterity = request('dexterity');
$edited_character->Constitution = request('constitution');
$edited_character->Intelligence = request('intelligence');
$edited_character->Wisdom = request('wisdom');
$edited_character->Charisma = request('charisma');
$levelVar = request('level');
if ($levelVar >= 4) {
$edited_character->Proficiency = 2;
} else if ($levelVar >= 8) {
$edited_character->Proficiency = 3;
}
$edited_character->Trained_Skills = request('skillsField');
$edited_character->Languages = request('languagesField');
$edited_character->Hit_Die = 1;
$edited_character->max_HP = request('max-hp');
$edited_character->Alignment = request('alignment');
$edited_character->Armor_Class = request('armor-class');
$edited_character->Initiative = request('initiative');
$edited_character->Speed = request('speed');
$edited_character->Background = request('background');
if($edited_character->save()){
return redirect('./characters');
}else{
// show error message
}
}
How to implode and insert values into the database in CodeIgniter?
I am creating multiple choice quiz script using CodeIgniter framework. I want to store user results like this:
id userid q_id answer_id time_taken
1 1 1,2,3,4,5 2,3,4,5,3 4,5,7,6,7
in my controller:
public function insert_result()
{
$this->load->model('quiz_models');
$user_id=$this->input->post('user_id');
$qq_id=$this->input->post('questionid');
$answer_id=$this->input->post('AnswerID');
$time_taken=$this->input->post('timetaken');
$question_no=$this->input->post('question_no');
$bd = "$question_no";
switch ($bd) {
case"1":
$data=array('user_id'=>$user_id,
'q_id'=>$qq_id,
'answer_id'=>$answer_id,
'time_taken'=>$time_taken);
$this->quiz_models->insert_result($data);
break;
case"2":
quiz_test();
break;
case"3":
quiz_test();
break;
case"4":
quiz_test();
break;
case"5":
quiz_test();
$this->session->unset_userdata('lastids');
break;
default:
echo "something is wrong";
}
}
public function quiz_test()
{
$this->load->model('quiz_models');
$quiz=$this->quiz_models->quiz_test();
foreach($quiz as $row){
$qid=$row->q_id;
$ans=$row->answer_id;
$time=$row->time_taken;
$a = array("$qq_id","$qid");
$b = array("$answer_id","$ans");
$c = array("$time_taken","$time");
$comma = implode(",",$a);
$comma1 = implode(",",$b);
$comma2 = implode(",",$c);
$data=array('q_id'=>$comma,
'answer_id'=>$comma1,
'time_taken'=>$comma2);
$this->quiz_model->update_result($data);
}
}
}
and Model:
function insert_result($data)
{
$this->dbb->insert('results',$data);
$sectio=$this->db->insert_id();
$this->session->set_userdata('lastids',$sectio);
}
function quiz_test()
{
$ses_id = $this->session->userdata('lastids');
$sql = "SELECT q_id, answer_id, time_taken FROM results WHERE id='$ses_id'";
$query = $this->dbb->query($sql);
$result = $query->result();
return $result;
}
function update_result($data){
$ses_id = $this->session->userdata('lastids');
$this->db->where('id',$ses_id);
$this->db->update('results',$data);
}
when i run it nothing happened,not showing any error where do i mistake?
pls help me what am i doing wrong
First of all - i think you've a major problem in your DB structure
Normalize your Data
You should prevent to store your information in the table like that.
It should be possible to normalize your data properly. If you dont know
how to do that the following link could be interesting:
Normalization in MYSQL
However a possible solution would be to structure your data:
In order to do that - create a save Method in your Model to split between update and insert - this model could look like
class Quiz_Models
{
private $arrPostData;
public function save($arrPostData = false)
{
$this->arrPostData = (!$arrPostData) ? $this->input->post() : $arrPostData;
$id = $this->session->userdata("lastids");
if ($id)
{
$query = $this->db
->select("*")
->from("results")
->where("id",$id)
->get();
if ($query->num_rows() == 1)
{
$this->update($query->row(0));
}
else return false;
}
else
{
$this->insert();
}
if ($this->arrPostData['question_no'] == 10) $this->session->unset_userdata("lastids");
}
private function update($objData)
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $objData->userid;
$objCollection->id = $objData->id;
$arrData = explode($objData->q_id);
foreach($arrData AS $key => $quizId)
{
$objQuiz = new stdClass();
$objQuiz->q_id = $quizId;
$objQuiz->answer_id = explode($objData->answer_id)[$key];
$objQuiz->time_taken = explode($objData->answer_id)[$key];
$objCollection->append($objQuiz);
}
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db
->where("id",$objCollection->id)
->update("results",$objCollection->getDbData());
}
private function insert()
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $this->arrPostData['user_id'];
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db->insert("results",$objCollection->getDbData());
$this->session->set_userdata("lastids", $this->db->insert_id());
}
}
as an addition you need a Collection Object (put this below your model)
class Quiz_Collection extends Array_Object
{
public $userId = 0;
public $id = 0;
public function addQuizFromPost($objQuiz)
{
if (intval($objQuiz->q_id) > 0)
{
foreach($this AS $key => $obj)
{
if ($obj->q_id == $objQuiz->q_id)
{
$this->offsetSet($key, $objQuiz);
return true;
}
}
$this->append($objQuiz);
return true;
}
return false;
}
public function sortQuizData($objA, $objB)
{
if ($objA->q_id == $objB->q_id) return 0;
return ($objA->q_id < $objB->q_id) ? -1 : 1;
}
public function getDbData()
{
$this->uasort(array($this,"sortQuizData"));
$arrData = $this->getArrayCopy();
$arrDbData = [
"userid" => $this->userId,
"q_id" => implode(array_map(function($obj){ return $obj->q_id;},$arrData),","),
"answer_id" => implode(array_map(function($obj){ return $obj->answer_id;},$arrData),","),
"time_taken" => implode(array_map(function($obj){ return $obj->time_taken;},$arrData),","),
];
return $arrDbData;
}
}
pS: this is just an instruction how you can do that in a proper way. Pls study this code. If you still don't understand whats going on, feel free to ask.
I couldn't find any proper example how to execute multiple insert query in codeigniter. I already tried make a function in models, containing more than 1 insert query. What I get always first query success, and others not executed at all.
I've already try use transaction: $this->db->trans_start();
In my case below: $db->trans_start(); and off course $db->trans_complete();
But that didn't help. Always only first insert query that executed. What should I do to execute all insert/update/delete queries in one fuction?
Example:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Deposit_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
public function inputdeh()
{
$this->load->helper('url');
$CI =& get_instance();
$db = $CI->load->database( 'local', TRUE );
$id_member = $this->input->post('id_member');
$jumlah = $this->input->post('jumlah');
$ket1 = $this->input->post('ket');
$ket = 'WEB/'.$ket1;
$saldoawal = $db->query("select saldo from member where id_member='$id_member'");
$saldoawa['saldo'] = $saldoawal->row('saldo');
$saldoaw = $saldoawa['saldo'];
$saldoak = $saldoaw + $jumlah;
//$_POST[jumlah]=number_format($_POST['jumlah'],".");
//$saldoak = number_format($saldoak);
//$dep = number_format(floatval($jumlah));
$result = $db->query("select nama from member where id_member='$id_member'");
$namar['nama'] = $result->row('nama');
$nama = $namar['nama'];
$resulthp = $db->query("select hp from member_hp where id_member='$id_member' LIMIT 1 OFFSET 0");
$hpr['hp'] = $resulthp->row('hp');
$nohp = $hpr['hp'];
//$now = 'NOW()';
$user = 'adminweb';
$data = array(
'id_member' => $this->input->post('id_member'),
'nama' => $nama,
'jml' => $this->input->post('jumlah'),
'saldo_awal' => $saldoaw,
'saldo_akhir' => $saldoak,
'kode_trx' => '1',
'status' => '1',
'ket' => $ket,
'user_input' => $user,
);
$db->set('tgl_transaksi', 'NOW()', FALSE);
$db->set('tgl_input', 'NOW()', FALSE);
return $db->insert('transaksi', $data);
$logsaldodata = array(
'id_member' => $this->input->post('id_member'),
'saldo' => $saldoaw,
'act' => $this->input->post('jumlah'),
'ket' => 'Deposit Tambah~True#',
);
$db->set('tgl', 'NOW()', FALSE);
$db->set('ref', 'last_insert_id()', FALSE);
return $db->insert('log_saldo', $logsaldodata);
}
}
Of course, you're returning before executing the rest of the code!
$db->set('tgl_input', 'NOW()', FALSE);
return $db->insert('transaksi', $data); // <-- remove the keyword here
$logsaldodata = array(
Remove that intermediate return statement, just leave $db->insert('transaksi', $data). return stops the function and returns the result, the rest of the function code won't be executed.