I'm using codeigniter;
I would like to get last N rows from my table.
In my query I want to get last 200 rows:
$this->m_general->select('count(*)');
$this->m_general->from('pm');
$result_count_query = $this->m_general->get();
$count_query = $result_count_query->num_rows();
$data['all'] = $this->m_general->get('pm', array( 'admin_delete'=>0 ) , $count_query-200,$count_query, array('admin_seen'=>'asc' , 'id'=>'desc') );
but it returns nothing.
where is my wrong ?
updated
below query not worked fine and it returns all records :
$data['all'] = $this->m_general->get('pm', array( 'admin_delete'=>0 ) ,200, array('admin_seen'=>'asc' , 'id'=>'desc') );
This Solve the Problem
$query = $this->db->query("SELECT * FROM pm WHERE admin_delete= 0 AND admin_seen=0 ORDER BY id DESC LIMIT 200");
$result = $query->result_array();
$count = count($result);
if(empty($count))
{
echo 'array is empty';
}
else{
return $result;
}
Check out the API
https://ellislab.com/codeigniter/user-guide/database/active_record.html
Looks like you can't do this with the get method.
Build your query according to the API.
$this->m_general->limit(200);
$this->m_general->order_by("admin_seen", "asc");
$this->m_general->order_by("id", "desc");
$data['all'] =
$this->m_general->get('pm', array( 'admin_delete'=>0 ));
Related
I have a issue.
My sql query don't work in codeigniter, when i try to order by specific value
Here's example:
$this->db->select('*');
$this->db->from('Questions');
$this->db->where('Questions.Status !=', 0);
$this->db->order_by('IdQuestion', 'DESC');
$this->db->order_by('(CASE WHEN Status = 3 THEN 1 ELSE 2 END)', 'DESC'); //Here's wrong...
But i don't receive valid result.
Someone can help.
Second order_by statement is wrong.
CASE don't work correct.
You can try this solution for your problem :
<?php
$sub_query_from = '(SELECT Questions.*, (CASE WHEN Questions.Status = 3 THEN 1 ELSE 2 END) as questions_status from Questions WHERE Questions.Status != 0 ORDER BY IdQuestion DESC) as sub_questions';
$this->db->select('sub_questions.*');
$this->db->from($sub_query_from);
$this->db->order_by('sub_questions.questions_status', 'DESC');
$query = $this->db->get();
$result = $query->result();
echo "<per>";
print_r($result);
exit;
?>
Hope it will helps.
My solutions is that:
To create view which will contains all results ordered, before select this view in codeigniter model
Example:
select (case when (`parajurist`.`intrebari`.`Status` = 2) then 1 else 2 end)
AS `Second`,`parajurist`.`intrebari`.`IdIntrebare` AS
`IdIntrebare`,`parajurist`.`intrebari`.`Titlu` AS
`Titlu`,`parajurist`.`intrebari`.`Descriere` AS
`Descriere`,`parajurist`.`intrebari`.`NumePrenumeP` AS
`NumePrenumeP`,`parajurist`.`intrebari`.`EmailP` AS
`EmailP`,`parajurist`.`intrebari`.`Status` AS
`Status`,`parajurist`.`intrebari`.`IdCategorie` AS
`IdCategorie`,`parajurist`.`intrebari`.`DataAdresare` AS
`DataAdresare`,`parajurist`.`intrebari`.`Comments` AS
`Comments`,`parajurist`.`intrebari`.`CuvCheie` AS `CuvCheie` from
(`parajurist`.`intrebari` join `parajurist`.`intrebaricategorii`
on((`parajurist`.`intrebaricategorii`.`IdCategorie` =
`parajurist`.`intrebari`.`IdCategorie`))) where
(`parajurist`.`intrebari`.`Status` <> 0) order by (case when
(`parajurist`.`intrebari`.`Status` = 2) then 1 else 2
end),`parajurist`.`intrebari`.`IdIntrebare` desc
and codeigniter code:
$this->db->limit($start, $stop);
$this->db->select('*');
$this->db->select('LEFT(intrebari_view.Titlu, 50) as Titlu');
$this->db->select('LEFT(intrebari_view.Descriere, 150) AS Descriere');
$this->db->join('IntrebariCategorii', 'IntrebariCategorii.IdCategorie = intrebari_view.IdCategorie');
$this->db->where('IntrebariCategorii.NumeCategorie', $cat);
$this->db->from('intrebari_view');
$query = $this->db->get();
$array = array('classesID' => 6);
$this->db->select()->from($this->_table_name)->where($array)->order_by($this->_order_by);
$query = $this->db->get();
return $query->result();
I need to get the rows where the classesID is 6. Some rows contain 6,5,4.
so i need to use FIND_IN_SET query to retrive where the classesID is 6.
Please guide me
Thanks
I need to get the rows which has student id '4488' and message id '1418'
$id = 1418;
$student_id = 4488;
this->db->select('id, action_status, updated_on, student_ids');
$this->db->where('message_id', $id);
$this->db->where('find_in_set("'.$student_id.'", student_ids) <> 0');
$this->db->from('actions_history');
$query = $this->db->get();
It will return a query like
SELECT id, action_status, updated_on, student_ids FROM actions_history WHERE message_id = '1418' AND find_in_set("4488", student_ids) <>0
Try this
$array = array('classesID' => '5,6,7');
$this->db->select();
$this->db->from($this->_table_name);
$this->db->where("FIND_IN_SET('classesID',".$array['classesID'].")",null,false);
$this->db->order_by($this->_order_by);
$query = $this->db->get();
return $query->result();
You can write the query like this.
return $this->db->where('classesID' , '6')->order_by('column_name','desc')->get('table_name')->result_array();
if Need any help comment
For those who're looking for model (CI v4.x) based solution,
$modal->where("FIND_IN_SET('<string to find>', '<column name>')", null, false)->findAll();
In your case,
$modal->where("FIND_IN_SET('".$array['classesID']."', 'classesID')", null, false)->findAll();
What would be wrong with my active record query the SUM function works fine but the count parts returns the count of all records.
$this->db->select(
'
t1.account_balance,
t2.CustomerName AS customer,
t2.CustomerId,
SUM(IF(t3.Bargain="Sale",t3.TotalAmount,0)) AS total_sale,
SUM(IF(t3.Bargain="Purchase",t3.TotalAmount,0)) AS total_buy,
COUNT(IF(t3.Bargain="Sale",t3.Bargain,0)) AS count_sale,
COUNT(IF(t3.Bargain="Purchase",t3.Bargain,0)) AS count_buy,
'
,FALSE);
$this->db->from("balances AS t1");
$this->db->join("customer AS t2","t2.CustomerId = t1.customer_id","left");
$this->db->join("gold_order AS t3","t3.CustomerId = t2.CustomerId","left");
$this->db->group_by("t3.CustomerId");
$object = $this->db->get();
Result:
What I want the count_sale should be 3 and count_buy should be 4:
try this
$this->db->select(
'
t1.account_balance,
t2.CustomerName AS customer,
t2.CustomerId,
SUM(IF(t3.Bargain="Sale",t3.TotalAmount,0)) AS total_sale,
SUM(IF(t3.Bargain="Purchase",t3.TotalAmount,0)) AS total_buy,
SUM(IF(t3.Bargain="Sale",1,0)) AS count_sale,
SUM(IF(t3.Bargain="Purchase",1,0)) AS count_buy,
'
,FALSE);
$this->db->from("balances AS t1");
$this->db->join("customer AS t2","t2.CustomerId = t1.customer_id","left");
$this->db->join("gold_order AS t3","t3.CustomerId = t2.CustomerId","left");
$this->db->group_by("t3.CustomerId");
$object = $this->db->get();
Try this:
$this->db->select('
t1.account_balance,
t2.CustomerName AS customer,
t2.CustomerId,
SUM(IF(t3.Bargain="Sale",t3.TotalAmount,0)) AS total_sale,
SUM(IF(t3.Bargain="Purchase",t3.TotalAmount,0)) AS total_buy,
(SELECT count(*) from gold_order where gold_order.Bargain="Sale") AS count_sale,
(SELECT count(*) from gold_order where gold_order.Bargain="Purchase") AS count_buy,
'
,FALSE);
$this->db->from("balances AS t1");
$this->db->join("customer AS t2","t2.CustomerId = t1.customer_id","left");
$this->db->join("gold_order AS t3","t3.CustomerId = t2.CustomerId","left");
$this->db->group_by("t3.CustomerId");
$object = $this->db->get();
Dear all friends i am new in Codeigniter framework i want total amount by selecting two table data, the problem is that when i enter data in 2nd table than total will double.
function total_amount($booking_no = NULL)
{
$data = array('forwarding_cargo_booking_details.*',
'other_charges.client_amount');
$this->db->select($data);
$this->db->where('forwarding_cargo_booking_details.booking_no',$booking_no);
$this->db->join('other_charges','forwarding_cargo_booking_details.booking_no = other_charges.booking_no','left');
$this->db->select('sum((`bk_m3`*`o_freight_client`)*(`selling_rate`)+`pod_client`+`thc_client`+`caf_client`+`baf_client`+`haulage_client`+`war_risk_client`+`warehouse_client`+`thc_dest_client`+`pp_surcharge_client`+`doc_charges_client`+`client_amount`) as salam', FAlSE);
$query = $this->db->get('forwarding_cargo_booking_details');
if($query->num_rows() > 0)
{
return $query->row();
}
}
Change it to this. Here use derieved query and test if it works ok
function total_amount($booking_no = NULL)
{
$sql_query = "SELECT
forwarding_cargo_booking_details.*,
other_charges.client_amount,
sum((`bk_m3`*`o_freight_client`)*(`selling_rate`)+`pod_client`+`thc_client`+`caf_client`+`baf_client`+`haulage_client`+`war_risk_client`+`warehouse_client`+`thc_dest_client`+`pp_surcharge_client`+`doc_charges_client`+`client_amount`) as amount
FROM forwarding_cargo_booking_details
LEFT JOIN (SELECT booking_no , sum(client_amount) FROM other_charges group by booking_no) as other_charges ON forwarding_cargo_booking_details.booking_no = other_charges.booking_no
";
$query = $this->db->query();
if($query->num_rows() > 0)
{
return $query->row();
}
}
use this code to print the query, and check the query.
$this->db->last_query();
i think you forget to use "Group By" in your query
This is my simple query in mysql/zend:
// Get Patients
$table = new Model_Patient_DbTable();
$select = $table->select();
$select->from( 'patient' );
$select->setIntegrityCheck( false );
// insurance join
$select->joinLeft( 'insurance', 'patient.insuranceId=insurance.Id',
array( 'insName' => 'insName'));
// Get total no of records
$totalRecords = count( $table->fetchAll( $select ) );
// Filters
if( $inactive ) {
$select->where('patient.inactive = ?', $inactive );
}
// Other where clause conditions
// Fetch filtered patient records
$patientRecords = $table->fetchAll( $select );
// Get total no of filtered patient records
$filteredRecords = count( $table->fetchAll( $select ) );
In above zend query I am get getting patient records and their insurances based on some conditions in where clause. I have to get (1) Total No. of Records, (2) Total No. of filtered Records and also (3) Patient Records to show on webpage.
Problem is that in my above query I have to fetch records 3 times which slow the performance when there are 10,000 records. How can I optimize my query that it fetch the the records only once OR there should be a separate query for counting that will only get total No of records instead of fetching all records.
Every reply will be appreciated.
Thanks
Thanks
Something like this should get you started, unfortunately I don't have a way of testing this currently.
// Get Patients
$table = new Model_Patient_DbTable();
// Get Total records
$select = $table->select();
$select->from($table, array('COUNT(*) as row_count'));
$select->setIntegrityCheck(false);
$select->joinLeft('insurance', 'patient.insuranceId = insurance.Id', array('insName' => 'insName'));
$result = $table->fetchAll($select);
$totalRecords = $result[0]->row_count;
// Filters
if ($inactive) {
$select->where('patient.inactive = ?', $inactive);
}
// Get Total filtered records
$result = $table->fetchAll($select);
$filteredRecords = $result[0]->row_count;
// Get filtered records
$select = $table->select();
$select->from($table);
$select->setIntegrityCheck(false);
$select->joinLeft('insurance', 'patient.insuranceId = insurance.Id', array('insName' => 'insName'));
if ($inactive) {
$select->where('patient.inactive = ?', $inactive);
}
$patientRecords = $table->fetchAll($select);
Note: You may be able to re-use the same Zend_Db_Select object by overwriting the $select->from() to remove the COUNT(*) addition.