Codeigniter - Model, checking that values are in row - php

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

Related

Multiple filter using codeigniter, i need only approved product?

i am doing multiple search using codeigniter, but all product are display from database. i only need approved product.
when i tried to display in product view page all the product are display from product table.
Controller:
public function product()
{
$searchText="";
if($this->input->post('searchText'))
{
$searchText = $this->input->post('searchText');
}
$like = array(
'ProductName'=>$searchText
);
$orlike = array(
'CategoryName'=>$searchText,
'SubCategoryName'=>$searchText,
'BrandName'=>$searchText
);
$where = array{
'ProductIsActive'=>1,
'ProductStatus'=>'Approved'
);
$jointables = array(
'categories'=>'CategorySlug=ProductCategory',
'subcategories'=>'SubCategorySlug=ProductSubCategory',
'brands'=>'BrandSlug=ProductBrand'
);
$data['product']= $this->
Custom_model-> getproduct('products',$jointables,$where,$like,$orlike,array());
}
Model:
function getproduct($primarytable,$jointables,$where,$like,$orlike)
{
$this->db->select('*');
$this->db->from($primarytable);
$this->db->where($where);
$this->db->like($like);
foreach($orlike as $key=>$value)
{
if($value!="")
{
$this->db->or_like($key,$value,'both');
}
}
foreach($jointables as $key=>$value)
{
$this->db->join($key,$value,'left');
}
$query = $this->db->get();
if($query->num_rows() > 0)
{
$row = $query->result();
return $row;
}else{
return FALSE;
}
}
The thing is in your configuration - if you have fields whiche are required you have to group your query
the following should do the job
your controller
public function product()
{
$searchText="";
if($this->input->post('searchText'))
{
$searchText = $this->input->post('searchText');
}
$arrFilter = [
'like' => [
'ProductName' => $searchText
],
'orlike' => [
'CategoryName' => $searchText,
'SubCategoryName' => $searchText,
'BrandName' => $searchText
],
];
$jointables = [
'categories'=>'CategorySlug=ProductCategory',
'subcategories'=>'SubCategorySlug=ProductSubCategory',
'brands'=>'BrandSlug=ProductBrand'
];
$where = [
'ProductIsActive'=>1,
'ProductStatus'=>'Approved'
];
$data['product']= $this->Custom_model-> getproduct('products',$jointables,$where,$arrFilter);
}
your model
function getproduct($primarytable, $jointables, $where, $arrFilter = [])
{
$this->db->select('*');
$this->db->from($primarytable);
$this->db->where($where);
if (is_array($arrFilter) && count($arrFilter) > 0)
{
$this->db->group_start();
if (isset($arrFilter['like']))
{
$this->db->like($arrFilter['like']));
}
if (isset($arrFilter['orlike']))
{
$this->db->group_start();
foreach($arrFilter['orlike'] as $key=>$value)
{
if($value!="")
{
$this->db->or_like($key,$value,'both');
}
}
$this->db->group_end();
}
$this->db->group_end();
}
foreach($jointables as $key=>$value)
{
$this->db->join($key,$value,'left');
}
$query = $this->db->get();
if($query->num_rows() > 0)
{
$row = $query->result();
return $row;
}
else
{
return FALSE;
}
}

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

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