codeigniter update db with custom_result_object() - php

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"));

Related

How to pass values from a assigned variable to view?

I wanted to pass some values to the view.
The $result may be 0 or 1 or '' and I tried to use this below code:
public function whatwedo($result='')
{
$result = array();
$result['status'] = $result;
$this->load->view('admin/whatwedo',$result);
}
public function add_whatwedo()
{
//$this->load->library('form_validation');
$this->form_validation->set_rules('text-input','Title','required');
if($this->form_validation->run() != true)
{
$result = 0;
$this->whatwedo($result);
}
else
{
$this->load->model('admin_model');
$result = $this->admin_model->ins_whatwedo($this->input->post());
//print_r($result);exit();
$this->whatwedo($result);
}
}
And in the view:
<?php
print_r($status);
?>
But, the $status is Array ( )
The problem is this line:
$result = array();
Because now the $result variable is an empty array so when you create the index status on result you assign it an empty array.
To fix you can do something like:
public function whatwedo($input = '')
{
$result['status'] = $input;
$this->load->view('admin/whatwedo', $result);
}
or even...
public function whatwedo($input = '')
{
$this->load->view('admin/whatwedo', ["status" => $input]);
}

How to get and insert ID CodeIgniter

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;
}
}
}

CodeIgniter - Checking to see if a slug already exists in the database

I Have made a function add_items. and I Want if the slug already exists in the database then the form_validation runs and shows the error message. and that's work fine if the slug exists. But the main problem is that if I want to insert the new Data in the database which obviously has a different slug then the data is not inserted.
public function add_items()
{
if($this->input->post()){
if($this->input->is_ajax_request()){
$title = $this->input->post('title');
$url_title = url_title($title);
$this->form_validation->set_rules($url_title,'callback_slug_exists');
if($this->form_validation->run() == FALSE)
{
echo "FAIL::Slug Already Exist::error";
return;
}
$item_price = $this->input->post('item_price');
$item_description = $this->input->post('item_description');
$insertData = array('item_title' =>$title,'item_url'=>$url_title,'item_price' =>$item_price,'item_description'=>$item_description,
'big_pic' =>$image_path."/".$image);
$result = $this->common_model->insert_record('store_items',$insertData);
if($result){
echo "OK::Record Inserted Successfully::success";
return;
}
else {
echo "FAIL::Record Insertion Failled::success";
return;
}
}
}
$this->show('admin/add_items.php');
}
Here are The function slug_exists()
function slug_exists($slug)
{
$this->common_model->slug_exists($slug);
}
This is in Model
function slug_exists($slug)
{
$this->db->where('item_url',$slug);
$query = $this->db->get('store_items');
if ($query->num_rows() > 0){
return true;
}
else{
return false;
}
}
This is the insert_record()
function insert_record($tbl, $data)
{
$this->db->insert($tbl, $data);
return $this->db->insert_id();
}
And this is DB Structure
try this:you can post data direct in an array. no need define it.
$insertArray=array(
item_title' =>$this->input->post('title'),
'item_url'=>$this->input->post('url_title'),
'item_price' =>$this->input->post('item_price'),
'item_description'=>$this->input->post('item_description'),
'big_pic' =>$image_path."/".$image);
$this->db->insert('store_items', $insertArray);
Try like this
function slug_exists($slug)
{
$this->db->where('item_url',$slug);
$query = $this->db->get('store_items');
if ($query->num_rows() > 0){
return false;
}
else{
return true;
}
}
If slug already exists then you need to fail the validation to get the error so return false on existing
Also, return the answer/result to a callback function
function slug_exists($slug)
{
return $this->common_model->slug_exists($slug);
}
Update
Controller
if($this->form_validation->run() == FALSE){
echo "FAIL::Slug Already Exist::error";
return;
}else{
$item_price = $this->input->post('item_price');
$item_description = $this->input->post('item_description');
$insertData = array('item_title' =>$title,'item_url'=>$url_title,'item_price' =>$item_price,'item_description'=>$item_description,
'big_pic' =>$image_path."/".$image);
$result = $this->common_model->insert_record('store_items',$insertData);
if($result){
echo "OK::Record Inserted Successfully::success";
return;
}
else {
echo "FAIL::Record Insertion Failled::success";
return;
}
}

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');

Codeigniter custom form_validation

I have a added custom function to the system->libraries->Form_validation.php
public function serial_exist($str, $value)
{
list($table, $column) = explode('.', $value, 2);
$query = $this->CI->db->query("SELECT COUNT(*) AS count FROM $table WHERE $column = '$str'");
$row = $query->row();
if ($row->count > 0) {
$query = $this->CI->db->query("SELECT COUNT(*) AS count FROM v_redeem WHERE v_serial='$str'");
$row = $query->row();
if ($row->count > 0) {
/// used
return FALSE;
} else {
return TRUE;
}
} else {
//invalid serial
return FALSE;
}
}
The I call the function from the below.
$this->form_validation->set_rules('serial','serial','required|xss_clean|serial_exist[v_info.v_serial]');
This works just fine but my issue how can I get the to different MSG say'n either invalid or used serial?
Hope my question is clear.
Try to set a custom set_message.
like this---
$this->form_validation->set_message('serial_exist', 'Your custom Message.');

Categories