Getting the rowid after adding an item with CI cart? - php

On the codeigniter website it says the the insert() method will return a $rowid of the latest inserted product. However How exactly do I grab it?
$data = array();
$insert = $this->cart->insert($data);
I tried $insert['rowid'] and $insert->rowid but neither seem to work.
Thank you!

introducing: insert_id()
like this
$id = $this->db->insert_id();
return $id;
in your model, lets call it friend_model
function insertRow()
{
// Prepare data, normally you would pass this in
$data = array(
'first' => 'john',
'last' => 'smith'
);
// insert data
$this->db->insert( 'friends', $data );
// confirm insert
if ( $this->db->affected_rows() == '1' )
// return new ID
{ $id = $this->db->insert_id();
return $id; }
// else did not insert, return false
else {return FALSE;}
}
in your controller, check if you got an id back from model
if(! $id = $this->friend_model->insertRow() )
// it no work
{ // some error method
}
else
{ // success !
}

Related

how to run two statements in one funcation

I'm trying to delete from two tables using one function.
Controller code:
public function userdelete()
{
$u_id = $this->uri->segment(3);
$lr_id = $this->uri->segment(3);
$returndata = $this->user_model->user_delete($u_id, $lr_id);
if($returndata) {
$this->session->set_flashdata('successmessage', 'user deleted successfully..');
redirect('users');
} else {
$this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
redirect('users');
}
}
Modle code:
public function user_delete($lr_id, $u_id ) {
return $this->db->delete('login_roles',['lr_id'=>$lr_id]);
return $this->db->delete('login',['u_id'=>$u_id]);
}
I'm able to delete only from the first table but not the other one. this is working :
return $this->db->delete('login_roles',['lr_id'=>$lr_id]); but not return $this->db->delete('login',['u_id'=>$u_id]);.
As said in the comment you have to remove the first return.
You should compute the two results :
public function user_delete($lr_id, $u_id ) {
$delete1Response = $this->db->delete('login_roles',['lr_id'=>$lr_id]);
$delete2Response = $this->db->delete('login',['u_id'=>$u_id]);
return ($delete1Response AND $delete2Response);
}
It will returns true only if both are deleted
You even can go further and :
public function user_delete($lr_id, $u_id ) {
$delete1Response = $this->db->delete('login_roles',['lr_id'=>$lr_id]);
$delete2Response = $this->db->delete('login',['u_id'=>$u_id]);
return (object)array('role' => $delete1Response, 'user' => $delete2Response);
}
Then you can access to data like that :
$response = user_delete(...);
if ($response->role AND $response->user) {
// All fine
} else {
// One or both failed.
// Display error or do something
}
It never reaches the second $this->db->delete since its returns after executing the first one. Try:
public function user_delete($lr_id, $u_id ) {
if($this->db->delete('login_roles',['lr_id'=>$lr_id])){
//success, try the next one
return $this->db->delete('login',['u_id'=>$u_id]);
}
//failed
return false;
}

my values on one column wont update immediately after inserting data, but after refresh the values shows up

after I inserting data, what shows on the column table "Jumlah Hasil Perah" shows '0'. but after refreshing the browser, the value shows up the result.
here's the code
Model (m_hasilperah):
public function jumlahPerahSapi($id)
{
$this->db->select('hasilPerahPagi, hasilPerahSore');
$this->db->where('idSapi', $id);
$cek = $this->db->get('tb_hasilperah');
if ($cek) {
$this->db->set('jumlahPerah', "hasilPerahPagi + hasilPerahSore", FALSE);
$this->db->where('idSapi', $id);
$this->db->update('tb_hasilperah');
}
return false;
}
Controller
public function tambahHasilPerah(){
$idSapi = $this->input->post('idSapi');
$tglPerah = $this->input->post('tglPerah');
$hasilPerahPagi = $this->input->post('hasilPerahPagi');
$hasilPerahSore = $this->input->post('hasilPerahSore');
$jumlahPerah = $this->m_hasilperah->jumlahPerahSapi($idSapi);;
$data =
[
'idSapi' => $idSapi,
'tglPerah' => $tglPerah,
'hasilPerahPagi' => $hasilPerahPagi,
'hasilPerahSore' => $hasilPerahSore,
'jumlahPerah' => $jumlahPerah
];
$insert = $this->m_hasilperah->tambahHasilPerahModel($data, $idSapi);
if ($insert) {
redirect('C_hasilperah/tampilHasilPerah/' . $idSapi, 'refresh');
} else {
echo 'gagal';
}
}
Screenshot:
View after insert(before manual refresh)
View after manual refresh
Your Model method jumlahPerahSapi() every time returned false. Even if after the data update. Please look into this.
Your Model function jumlahPerahSapi($id) is always return false even inserted successfully in DB.
So This is not run redirect('C_hasilperah/tampilHasilPerah/' . $idSapi, 'refresh');
Every time run echo 'gagal';
Modify the model function as follows.
public function jumlahPerahSapi($id)
{
$this->db->select('hasilPerahPagi, hasilPerahSore');
$this->db->where('idSapi', $id);
$cek = $this->db->get('tb_hasilperah');
if ($cek) {
$this->db->set('jumlahPerah', "hasilPerahPagi + hasilPerahSore", FALSE);
$this->db->where('idSapi', $id);
$this->db->update('tb_hasilperah');
return true;
}
return false;
}

how to pass the data in the post so that we can call the id?

how to pass the data in the post so that we can call the id ?
because we are trying to get the "qtopic_id" of the question but its not working and it keeps on giving me a null value.
I have tried declaring qtopic_id= 19 to see if its saving in the qtopic_id column.
I don't have to put a specific id value to save on the following column so that it wont save on that specific id only but instead it will save on its corresponding qtopic_id.
controller
public function addChoices(){
$this->form_validation->set_rules('ques','Question','required');
$this->form_validation->set_rules('ch_des1','Choices','required');
$this->form_validation->set_rules('ch_des2','Choices','required');
$this->form_validation->set_rules('ch_des3','Choices','required');
$this->form_validation->set_rules('ch_des4','Choices','required');
$this->form_validation->set_rules('ans','Answer','required');
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if($this->form_validation->run() ){
echo $qtopic_id ;
$data['ques'] = ($this->input->post('ques'));
$data['ch_des1'] = ($this->input->post('ch_des1'));
$data['ch_des2'] = ($this->input->post('ch_des2'));
$data['ch_des3'] = ($this->input->post('ch_des3'));
$data['ch_des4'] = ($this->input->post('ch_des4'));
$data['ans'] = ($this->input->post('ans'));
if($id=$this->queries->registerChoices($data) )
{
$this->session->set_flashdata('message','Test Added Succesfully');
return redirect('admin/testtwo');
}
else {
$this->session->set_flashdata('message','Failed to Add Test');
}
return redirect('admin/testtwo');
}
else {
$this->addQuestion();
}
}
}
model:
----updated---
public function registerChoices($data) {
echo $this->input->post('qtopic_id');
$question_arr = [
'ques' => $data['ques'],
'qtopic_id' => 19
];
$choices_arr = [
'ques' => $data['ques'],
'ch_des1' => $data['ch_des1'],
'ch_des2' => $data['ch_des2'],
'ch_des3' => $data['ch_des3'],
'ch_des4' => $data['ch_des4'],
'ans' => $data['ans']
];
// echo "<pre>";
// var_dump($question_arr);
// var_dump($choices_arr);
// exit;
$this->db->insert('tbl_choices',$choices_arr);
$this->db->insert('tbl_question',$question_arr);
return $this->db->insert_id();
}
error messages that i encountered
Your code for register choices is a bit unclear. insert_id isn't a function that accepts data nor does it do inserting, it simply returns the last inserted id after you perform an insert query. I think what you want is something like:
function registerChoices($data) {
if ($this->db->insert('tablename', $data)) {
return $this->db->insert_id();
}
return false;
}
Usage:
$last_insert_id = $this->somemodel->registerChoices($data);
if ($last_insert_id) {
echo "item with id $last_insert_id was created!";
} else {
show_error('Query failed!');
}

how to check callback validation codeigniter duplicate database entry?

This is my callback function, I want to check the database for duplicate value, I have tried a lot, but I can't get validation to work. I'm new to Codeigniter so any help would be appreciated!
public function alias_exist_check()
{
$scol_code = $this->input->post('school_code');
$user_id=$this->input->post('user_id');
$query=$this->db->get_where('user_application',array('school_code'=>$scol_code, 'user_id'=>$user_id));
$row= $query->row_array();
if(!$row['user_id']==$user_id && !$row['school_code']==$scol_code)
{
return TRUE;
} else {
$this->form_validation->set_message('alias_exist_check', 'Already exists.');
return FALSE;
}
}
UPDATE1 ::
i tried this but its not working me help me if i wrote any mistakes.
$this->form_validation->set_rules('school_code', 'School Name','required','callback_alias_exist_check', 'trim|xss_clean'); $where = array(
'school_code' => $this->input->post('school_code'),
'user_id' => $this->input->post('post'));
if( ! $this->lawschool_model->alias_exist_check($where))
{
$this->form_validation->set_message('alias_exist_check', 'Already exists.');
}
if ($this->form_validation->run() == FALSE)
{
$data['row']= $this->lawschool_model->Getuser($data1);
$data['row1']= $this->lawschool_model->GetData1();
$this->ag_auth->view('Home',$data);
}
else
{
$insert = $this->db->insert('user_application',$data);
if($insert==TRUE)
{
/*$idNum = $this->input->post('school_code');
$data1 = $this->lawschool_model->upddata_school();*/
$data['row'] = $this->lawschool_model->Getuser($data1);
$data['row1'] = $this->lawschool_model->GetData1();
$this->ag_auth->view('Home',$data);
}
}
UPDATE2::finaly its works fine,here is my working code
$this->form_validation->set_rules('school_code', 'School Name','required','callback_alias_exist_check1', 'trim|xss_clean');
function alias_exist_check1($scol_code,$user_id)
{
$sql = "SELECT * FROM user_application WHERE school_code = ? AND user_id = ?";
$val = $this->db->query($sql,array($scol_code ,$user_id ));
if ($val->num_rows)
{
$this->form_validation->set_message('alias_exist_check', 'Already exists.');
return TRUE;
}
else
{
return FALSE;
}
}
Model
public function alias_exist($where)
{
return $this->db->where($where)->count_all_results('user_application') > 0;
}
Controller
public function alias_exist_check()
{
$where = array(
'school_code' => $this->input->post('school_code'),
'user_id' => $this->input->post('user_id')
);
return ! $this->name_model->alias_exist($where);
}
The first function was not working because you tried to access post data from within the callback itself. This does not appear to work well with callbacks. This is because codeigniter will remove all post data from the request as soon as your run the form validator run method. It repopulates post data only when form processing is complete. Pass any extra parameters you need for you callback functions to work like this
callback_foo[bar]

Returning NULL from query for datatables

I'm wondering what would be best to do. Right now I have running a query to see if I have any results returned and if none are returned I return NULL.
On my controller I send that resultset whether it be an object or NULL to my table and it echos the rows on the view page.
For my tables I am using the jquery datatables plugin. I'm trying to figure out how I can have it handle the data when the sent value is NULL that way it doesn't show me an error when it hits my foreach loop.
Controller:
$news_articles = $this->news_model->get_news_articles();
$this->data['news_articles'] = $news_articles;
Model:
/**
* Get news articles
*
* #return object
*/
function get_news_articles()
{
$query = $this->db->get($this->news_articles_table);
if ($query->num_rows() > 0) return $query->result();
return NULL;
}
View:
$tmpl = array ( 'table_open' => '<table class="table" id="newsarticles-table">' );
$data = array('name' => 'newsarticles', 'class' => 'selectall');
$this->table->set_heading(form_checkbox($data), 'ID', 'Date', 'Title');
$this->table->set_template($tmpl);
foreach ($news_articles as $row)
{
$checkbox_data = array(
'name' => 'newsarticles',
'id' => $row->id
);
$this->table->add_row(form_checkbox($checkbox_data), $row->id, $row->date_posted, $row->article_title);
}
echo $this->table->generate();
I typically respond using JSON and then add a "success" type boolean and then check that value before trying to process any data. It also allows for an easy way to place an error message in the response if something goes wrong.
Just another idea
Model
function get_news_articles()
{
$query = $this->db->get($this->news_articles_table);
if ($query->num_rows() > 0) return $query->result();
return FALSE;
}
Controller
$news_articles = $this->news_model->get_news_articles();
if(!$news_articles) $this->data['success'] = FALSE;
else
{
$this->data['news_articles'] = $news_articles;
$this->data['success'] = TRUE;
}
In the view
if($success)
{
foreach ($news_articles as $row)
{
//....
}
}
else echo "No results found !";
Just return an empty array from the model, if there are not results. That way your foreach won't break. It just won't loop over anything.

Categories