I have the following function in my model to filter officer records user wise. The function is working fine.
public function getOfficer()
{
$q = $this->db->order_by('last_name','ASC')->get_where('tbl_officer', array('status' => '1', 'usr' =>$this->session->userdata('id_user')));
if ($q->num_rows() > 0) {
return $q->result();
}
return false;
}
Further, I want to filter officer records only for the user = 4 in the session, by p_code->8,10 and 24
The If functions as follows :
if($usr == 4)
{
$this->datatables->where('tbl_officer.p_code', 8)->or_where('tbl_officer.p_code', 10)->or_where('tbl_officer.p_code', 24);
} else {
$this->datatables->where('tbl_officer.usr', $usr);
}
How can I include this If condition into my model function mentioned above ? What can be changed ? Can anyone help ?
PLease use where_in
$this->datatables->where('tbl_officer.p_code', 8)->or_where('tbl_officer.p_code', 10)->or_where('tbl_officer.p_code', 24);
to
$this->datatables->where_in('tbl_officer.p_code', [8,10,24]);
Just need to change the method of query writing
public function getOfficer()
{
$usr = $this->session->userdata('id_user');
$userArray = array(8,10,24);
$this->db->select('*');
$this->db->from('tbl_officer');
if($usr == 4){
$this->db->where_in('usr',$userArray );
}else{
$this->db->where('usr',$usr);
}
$q = $this->db->get();
if ($q->num_rows() > 0) {
return $q->result();
}
return false;
}
Related
I am working with rest api using codeigniter,I want to fetch records + total records + per page records,but not worked for me
Here is my function in controller
<?php
public function search_shop()
{
$users['rec'] = $this->Model_users->find_shop($_POST);
if($users['rec']!="")
{
$responseJSON = array("Status" => true,"Result" => $users['rec']);
header("content-type:application/json");
$response = json_encode($responseJSON);
echo $response;
}
else
{
$responseJSON = array("Status" => false,"Message" => "There is no matching record");
header("content-type:application/json");
$response = json_encode($responseJSON);
echo $response;
}
}
And here is my "find_shop" function in model,How can i fetch all records with total number of records and per page records ?
public function find_shop()
{
$add_data['page_number'] = ($this->input->post('page_number') && !empty($this->input->post('page_number'))) ? $this->input->post('page_number') : NULL;
$add_data['search'] = ($this->input->post('search') && !empty($this->input->post('search'))) ? $this->input->post('search') : NULL;
$records="10";
$mins="10";
if($add_data['page_number']=="" || $add_data['page_number']=="0" || $add_data['page_number']=="1")
{
$starting_row="0";
$last_row="10";
}
else
{
$last_row="9";
$cd="1";
$lim="10";
$starting_row=$add_data['page_number']*$lim-$last_row-$cd;
$last_row=$add_data['page_number']*$records-$cd;
}
$this->db->select('*');
$this->db->from('shop s');
$this->db->like('shop_name',$add_data['search']);
$this->db->or_like('city',$add_data['search']);
$this->db->limit($last_row,$starting_row);
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
$row = $query->result_array();
return $row;
return $query->num_rows;
}
else
{
return false;
}
}
?>
Try This, Hope it helps
in the Controller please test this after model related changes
$users = array();
$users = $this->Model_users->find_shop($_POST);
echo'<pre>';print_r($users);die;
in the Model, There is a mistake in the return, You cannot do two return at the same time
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
$data = array();
$data['row'] = $query->result_array();
$data['total_records'] = $this->db->count_all_results('shop');
$data['per_page_records'] = $query->num_rows();
return $data;
}else{
return array('row'=>array(),'total_records'=>'0','per_page_records'=>'0');
}
Change your if condition like this:
$records="10"; // This is records per page showing
if ($add_data['page_number']=="" || $add_data['page_number']=="0" || $add_data['page_number']=="1")
{
$starting_row="0";
} else {
$starting_row = ($add_data['page_number'] - 1) * $records;
}
You need to set limit and offset of query. For example: limit 0, 10: this will show first 10 records. Here 0 is starting point and 10 is the length of records which you want to show. 10 will always be same as you are showing 10 records. Limit 10, 10: it will show records from 10 to 19. hope it clears your doubt.
I want to loop through the results of a query and then compare each results to an input field, if the value is repeated it must return false if not the result is true, I know that I could use unique index in database to avoid repeated values and then catch the error, but in this case repeated values are possible but they can´t both be "active" there a column called "status" with two values A or I (active and inactive) so "clabe" value can be repeated only when one is active and the other inactive.
Controller:
function agregar()
{
$this->load->helper('date');
date_default_timezone_set('America/Mexico_City');
$now = date('Y-m-d H:i:s');
$Interno = $this->input->post('intern');
$clabe = $this->input->post('clabe2') . $this->input->post('control2');
$cve_banco = $this->input->post('cve_banco');
$Banco = $this->input->post('Banco2');
$Observaciones = $this->input->post('Observaciones');
$data = array(
'Interno' => $Interno,
'clabe' => $clabe,
'cve_banco' => $cve_banco,
'Banco' => $Banco,
'Observaciones' => $Observaciones,
'Fecha_alta' => $now,
);
if($this->consultas_M->insert($data) == true){
//redirect('Inicio/busqueda', 'refresh');
} else{
echo "Hubo un problema al insertar";
}
}
Model:
function insert($data)
{
$clabe = $this->input->post('clabe2') . $this->input->post('control2');
$this->db->select('Clabe');
$this->db->where('Status =', 'A');
$query= $this->db ->get('cuentas');
return $query->row();
foreach ($query as $row) {
$i = $row;
if ($clabe = $i) {
return false;
} else {
$this-> db -> insert('cuentas', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
}
}
}
Why would you want to have possible duplicated index ? If you want to have different rows with a common "index" for some reason you can create a column called index or something and add in your WHERE clause that index.
PS: in your model in the foreach loop's if condition use :
if ($clabe == $row){...
instead of
$i = $row
if ($clabe = $i){...
I solved myself the issue, i´m posting in in case it helps anybody, it was easier than I thought.
function insert($data, $clabe)
{
$Status = 'A';
$clabe = $this->input->post('clabe2') . $this->input->post('control2');
$this->db->select('Clabe');
$this->db->where('Status =', $Status);
$this->db->where('Clabe =', $clabe);
$q= $this->db ->get('cuentas');
if($q -> num_rows() > 0){
return false;
}else{
$this-> db -> insert('cuentas', $data);
return true;
}
And this is the controller:
if($this->consultas_M->insert($data, $clabe) == true){
redirect('Inicio/busqueda', 'refresh');
} else{
echo "There was a problem";
$this->load->view('errors/error');
}
The only thing I needed and wasn´t doing was to select the "clabe" I wanted and then compare it with the input where user writes this "clabe". And then just a simple if-else statement.
function insert($data)
{
$Status = 'A';
$clabe = $this->input->post('clabe2') . $this->input->post('control2');
$this->db->select('Clabe');
$this->db->where('Status', $Status);
$query= $this->db ->get('cuentas');
$flag=true;
foreach ($query as $row) {
$i = $row;
if ($clabe = $i){
$flag=false;
}
}
if($flag){
$this-> db -> insert('cuentas', $data);
if ($this->db->affected_rows() > 0) {
$flag= true;
}
}
return $flag;
}
Your code will add it on first else block ad return. Instead it should check all the rows first to decide.
i want to make pagination on ci from other web reference, but average of them use only 1 table
does anyone know how to input more than 1 table on this condition
public function data($number,$offset){
return $query = $this->db->get('client',$number,$offset)->result();
}
i have try to input like this
public function data($number,$offset){
return $query = $this->db->get('client,advertisement,size',$number,$offset)->result();
}
but the result is not my expected
the NAMA is looping, the IKLAN too but the SIZE is not
i take the refences from here
I use this:
public function fetch_countries($limit, $start) {
$this->db->limit($limit, $start);
$this->db->join('client', 'advertisement.id_client= client.id_client','inner');
$this->db->join('size', 'advertisement.id_size= size.id_size','inner');
$query = $this->db->get("advertisement");
if ($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
Using Codeigniter 3, I would like to display all the records from a table in a MySQL database. I'd also like to include the number of records selected.
For example;
Showing x number of records;
record 1
record 2
record 3
etc
Currently I have the following (which works);
// select all records
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
// count all records
public function countRecords() {
$this->db->select('count(*) as count');
$this->db->from('records');
$query = $this->db->get();
return $query->row();
}
My question is do I need two separate queries in order to achieve this (select and count)?
Is there a more efficient way of achieving what I want?
You can do something like this :
public function selectRecords()
{
$query = $this->db->get('records');
if ($query->num_rows() > 0 )
{
$records = $query->result_array();
$data['count'] = count($records);
$data['all_records'] = $records;
return $data;
}
}
Pass it to the view from your controller :
$data = $this->model_name->selectRecords();
/*print_r($data) to see the output*/
$this->load->view('your_view',$data);
In view :
<?php echo $count .' number of records';?>
you can do only:
public function selectRecords() {
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
return $query->result_array();
}
and
$records = $this->selectRecords();
$count = count($records);
In The first function itself you can get the count using $query->num_rows() function
public function selectRecords() {
$return = array();
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
$return['count'] = $query->num_rows();
$return['records'] = $query->result_array();
return $return;
}
try this
it will help you to provide pagination for records
public function selectRecords($params = array(), $count = false) {
$offset = isset($params['offset']) ? $params['offset'] : '';
$limit = isset($params['limit']) ? $params['limit'] : '';
$this->db->select('*');
$this->db->from('records');
$query = $this->db->get();
if ($count) {
return $this->db->get()->num_rows();
}
if (empty($offset) && !empty($limit)) {
$this->db->limit($limit);
}
if (!empty($offset) && !empty($limit)) {
$this->db->limit($limit, $offset);
}
$result = $this->db->get()->result();
return $result;
}
I have some simple function to collect allowed array, but something is not ok, can somebody help me? Here is my code
public function getAllbyLink($table, $what, $url)
{
$link=mysql_real_escape_string($url);
$query = $this->db->query("SELECT * FROM ".$table." WHERE ".$what." = '{$link}' LIMIT 0 , 1");
if ($query->num_rows() > 0)
{
return $query->result();
}
else redirect('');
}
Please read something about MVC pattern, question is clearly pointed on how to write a Model.
consider using this function
public function getTable($table, $where = array(), $select = '*', $order_by = '', $limit = '', $offset = '') {
if ($order_by !== '' && $order_by != 'RANDOM') $this->db->order_by($order_by);
if ($order_by == 'RANDOM') $this->db->order_by('id', 'RANDOM');
if ($limit !== '') $this->db->limit($limit, $offset);
$this->db->select($select);
$q = $this->db->get_where($table, $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
for your purpose call the function like this:
getTable($talbe, array('what' => $link));
//returns FALSE if no data are selected,
//or returns object with data,
if you wish return array instead replace $q->result() with $q->array_result()
Please note that active record auto escapes.
After comments:
comment-1, you can simplify that function easily just delete what you do not need, for example
public function getTable2($table, $where = array(), $limit = '', $offset = '') {
if ($limit !== '') $this->db->limit($limit, $offset);
$q = $this->db->get_where($table, $where);
return ($q->num_rows() > 0) ? $q->result() : FALSE;
}
comment-2,when there is no data use this if-else statement
if (!$my_data = getTable2('table', array('where' => $link))) {
//there is some DATA to work with
echo "<pre>";
var_dump($my_data);
echo "</pre>";
} else {
//no DATA do redirect or tell user that there is no DATA
redirect(); //redirect to default_controller
}
comment-3, no comment;
comment-4, It also allows for safer queries, since the values are escaped automatically by the system. from this source. And another SO question about active record providing exact answer you are seeking.
My understanding of your code is:
Read all rows from table
Check if linkurl is in the list
If so, return a random row for that value
Else, redirect.
In this case, try this:
public function getAllbyLink($table,$url,$what)
{
$query = $this->db->query("
SELECT *
FROM `".$table."`
WHERE `".$what."` = '".mysql_real_escape_string($linkurl)."'
ORDER BY RAND()
LIMIT 1
");
if( !$query) return redirect('');
$result = $query->result();
if( !$result) return redirect('');
return $result;
}