How to get and insert ID CodeIgniter - php

I save my data like this
public function saveInvestors($id = 0)
{
$data = array ('id' => $id );
$data2 = array ('ref_id' => $data['id]);
if ($id == 0)
{
return [$this->db->insert('investor', $data), $this->db->insert('leveling', $data2)];
}
}
my id on $data is auto increment on database while id on $data2 is not my problem here is that I couldn't get the id on $data and insert it on leveling but it always returning 0

You need to get the inserted id after inserting it into the database:
$this->db->insert('investor', $data);
$new_id = $this->db->insert_id();
As seen in the documentation: https://codeigniter.com/user_guide/database/helpers.html

Try this.
public function saveInvestors($id = 0)
{
$data = array('id' => $id);
if ($id == 0) {
$this->db->trans_begin();
$this->db->insert('investor', $data);
$id_investor = $this->db->insert_id();
$data2 = array('ref_id' => $id_investor);
$this->db->insert('leveling', $data2);
if ($this->db->trans_status() === TRUE) {
$this->db->trans_commit();
return TRUE;
} else {
$this->db->trans_rollback();
return FALSE;
}
}
}

Related

codeigniter update db with custom_result_object()

I got a codeigniter custom_result_object with this:
$user = $this->CI->db->get_where('users', array('email' => $email), 1)->custom_row_object(0,'entities\User');
and everything looks fine. I can update values with my setters.
Before I'm going to save i check my values with:
die(print_r($user));
and the values are correct.
I put my object in my update method.
$this->CI->db->update('users', $user, "id = ".$user->getId());
But the db is not updating. Am I missing something?
Thx!
EDIT:
So by using CI native db-method i can use:
public function save($user)
{
if($user->getId() == NULL){
$this->CI->db->insert('users', $user);
}else{
$this->CI->db->update('users', $user, "id = ".$user->getId());
}
}
Edit 2:
After some more checking I can see that it's not setting variables that are protected. CI is able to get the object through getters and setters but not able to save back to DB?
public function saveData($tbl,$data,$update = false,$previewStr = false){
$set_str = "NO_QUOTES()";
if(isset($data[$set_str])){
foreach($data[$set_str] as $set_key => $set_value){
$this->db->set($set_key, $set_value, FALSE);
}
unset($data[$set_str]);
}
if(isset($update[$set_str])){
foreach($update[$set_str] as $whr_key => $whr_value){
$this->db->where($whr_key." ".$whr_value,NULL,false);
}
unset($update[$set_str]);
if(is_array($update) and count($update) <= 0){
$update = true;
}
}
if($update == false){
$this->db->insert($tbl, $data);
if($previewStr){
return $this->db->last_query();
}else{
return $this->db->insert_id();
}
}else{
$result = NULL;
if(!is_array($update)){
if(is_array($data) and count($data) > 0){
foreach($data as $field => $value){
$this->db->set($field, $value);
}
}
$result = $this->db->update($tbl);
}else{
$result = $this->db->update($tbl, $data,$update);
}
if($previewStr){
return $this->db->last_query();
}else{
return $result;
}
}
}
public function delData($tbl = false,$where = array()){
if($tbl !== false){
return $this->db->delete($tbl, $where);
}else{
return false;
}
}
public function simpleQuery($query,$return_array = false,$return_single = false)
{
$ac = $this->db->query($query);
if($return_array === false){
return $ac;
}else{
if($return_single === false){
return $ac->result_array();
}else{
return $ac->row_array();
}
}
}
Use above code in your model and you i am giving you how to update it use below code in your controller you can insert update and delete by above code
$result=$this->Products_model->saveData("customer",array("customer_name"=>$name),array("cust_id"));

how to write a function for fetching the record by sending only parameters in codeigniter?

I have 100 tables or can be more than that,I always need to fetch the record all the time in my application from various table.So writing functions for each and every query its not good coding standard.
$this->db->select();
$this->db->from("table1");
$query = $this->db->get();
return $query->result_array();
$this->db->select();
$this->db->from("table2");
$query = $this->db->get();
return $query->result_array();
$this->db->select();
$this->db->from("table1");
$this->db->where("id",10);
$query = $this->db->get();
return $query->result_array();
I want the good coding standard for this.
Write this code in controller.
$data = $this->common_model->getRecords("table_name", "*", array("field1" => $this->input->post('user_name')));
This will be your function in model (that is common_model).
public function getRecords($table, $fields = '', $condition = '', $order_by = '', $limit = '', $debug = 0) {
$str_sql = '';
if (is_array($fields)) { #$fields passed as array
$str_sql.=implode(",", $fields);
} elseif ($fields != "") { #$fields passed as string
$str_sql .= $fields;
} else {
$str_sql .= '*'; #$fields passed blank
}
$this->db->select($str_sql, FALSE);
if (is_array($condition)) { #$condition passed as array
if (count($condition) > 0) {
foreach ($condition as $field_name => $field_value) {
if ($field_name != '' && $field_value != '') {
$this->db->where($field_name, $field_value);
}
}
}
} else if ($condition != "") { #$condition passed as string
$this->db->where($condition);
}
if ($limit != "")
$this->db->limit($limit);#limit is not blank
if (is_array($order_by)) {
$this->db->order_by($order_by[0], $order_by[1]); #$order_by is not blank
} else if ($order_by != "") {
$this->db->order_by($order_by); #$order_by is not blank
}
$this->db->from($table); #getting record from table name passed
$query = $this->db->get();
if ($debug) {
die($this->db->last_query());
}
$error = $this->db->_error_message();
$error_number = $this->db->_error_number();
if ($error) {
$controller = $this->router->fetch_class();
$method = $this->router->fetch_method();
$error_details = array(
'error_name' => $error,
'error_number' => $error_number,
'model_name' => 'common_model',
'model_method_name' => 'getRecords',
'controller_name' => $controller,
'controller_method_name' => $method
);
$this->common_model->errorSendEmail($error_details);
redirect(base_url() . 'page-not-found');
}
return $query->result_array();
}
I used this code for fetching the record. you just need to pass the table name ,fields name ,the condition and limit.
your codes can actually be in 1 line
$query= $this->db->get('table1')->result_array();
$query= $this->db->get_where('table1', array('id'=>3,'name'=>'tom'))->result_array();
or if you really want a function
function getData($table){
$query=$this->db->get($table)->result_array();
return $query;
}
$data= getData('table1');

Joomla JTable Load Array and edit fields

I see that one can use an array with Jtable load, I tried the following:
public function delete($id = null) {
$app = JFactory::getApplication();
$id = $id ? $id : $app->input->get('files', array(), 'ARRAY');
$file = JTable::getInstance('Document','Table');
$file->load($id);
$file->date_removed = date("Y-m-d H:i:s",time());
if($file->store())
{
return true;
} else {
return false;
}
}
print_r($id) is:
Array
(
[0] => 1
[1] => 2
)
But I am having no luck. I keep getting the following error:
0 - Missing field in database: TableDocument   1.
Documentation on JTable
Any Help Greatly Appreciated.
Well actually you doing it wrong. You can load JTable with few field values, but it only returns 1 result;
Example use:
$data = array('id' => 100, 'user_id' => 101);
$table->load($data);
The code above will search for table entry with id = 100 AND user_id = 101. You cannot load 2 table entries like that.
My suggestion would be:
public function delete($id = null) {
$ids = array();
$return = true;
if ($id) {
$ids[] = $id;
} else {
$ids = JFactory::getApplication()->input->get('files', array(), 'ARRAY');
}
if (count($ids) > 0) {
foreach ($ids as $id) {
$file = JTable::getInstance('Document','Table');
$file->load($id);
$file->date_removed = date("Y-m-d H:i:s",time());
$temp = $file->store();
$return = $return || $temp;
}
}
return $return;
}

Add or edit data if already exist in database

Im trying to add or edit data depending if its already stored in the database. As you can see below im checking if user already exist with getuserid($id) loading the corresponding view but the problem is when i trigger add_user() or edit_user() as none of these methods are redirecting back as it should be. Any suggestions? This is the complete code http://pastebin.com/2G7D8ie4
public function getuserid($id = NULL){
if(!$id)
{
show_404();
}
$query = $this->Users_model->getuserid($id);
if($query == false){
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/add_users_view',
'id'=>$id);
}else{
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/edit_users_view',
'id'=> $query->id,
'staff_id'=> $query->staff_id,
'login'=> $query->login,
'password'=> $query->password
);
}
$this->load->view('themes/'.$this->config->item('theme_front').'.php', $data);
}
Model
public function getuserid($id){
$query = $this->db->get_where('users', array('staff_id' => $id));
if($query->num_rows() > 0){
return $query->row();
}else{
return false;
}
}
can you try making your model
public function getuserid($id){
$query = $this->db->get_where('users', array('staff_id' => $id));
$result=array();
foreach ($query->result() as $rows){
$result[]=$rows;
}
return $result;
}
and controller
if(count($query)>0){
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/edit_users_view',
'id'=> $query->id,
'staff_id'=> $query->staff_id,
'login'=> $query->login,
'password'=> $query->password
);
}
else
{
$data = array('title'=>'Admin ::LxFPanamá::',
'content'=>'users/add_users_view',
'id'=>$id
);
}

Codeigniter - Model, checking that values are in row

I need to check that two variables match fields in a row where the id = x.
Firstly I checked that the row with ID x exists I then need to check that both $category and $title are equal to the values in that row.
How can I compare the variables to the fields and return true if they match???
function match_id($category,$id,$title)
{
$this->db->where(array('id' => $id));
$query = $this->db->get('news');
if ($query->num_rows() > 0){
foreach ($query->result() as $row) {
$data = array(
'category' => $row->category,
'title' => $row->title
);
}
//If category == $category && title == $title, return true
return true;
}
else{
return false;
}
}
You can just do the matching in query itself:
$this->db->where(array('id' => $id,'title'=>$title,'category'=>$category));
$query = $this->db->get('news');
if ($query->num_rows() > 0){
return true;
}
else{
return false;
}
if ($data['category'] == $category && $data['title']==$title)
{
return TRUE;
}

Categories