Query in CodeIgniter with several where clauses - codeigniter

I'm trying to make a query with severel where clauses, but it gives wrong results. I need to see these users which have role_id=1 (that are students), which are not deactivated. I take $this->uri->segment(3) =teacher_id. And the third where clause is that I need only students that studies in the same school as the school of the teacher , which I take with $this->uri->segment(3). My query is:
public function select_students() {
$this->db->select('*');
$this->db->from('users');
$this->db->where('deactivated_at = "0000-00-00 00:00:00" || deactivated_at IS NULL
AND role_id =1 AND school_id = ("SELECT school_id FROM users WHERE user_id=$this->uri->segment(3)")');
$result=$this->db->get();
return $result->result();
}
I found solution:
public function select_students() {
$this->db->select('*');
$this->db->from('users');
$this->db->where('(users.deactivated_at = "0000-00-00 00:00:00" OR users.deactivated_at IS NULL) AND users.role_id = 1 ');
$this->db->where('users.school_id',$this->uri->segment(4) );
$result=$this->db->get();
return $result->result();
}

better use custom SQL and after that wrap with CI method. This will provide you flexibility to write any custom query as well as protect query with CI security.
public function select_students() {
$sql = SELECT * FROM users WHERE deactivated_at = "0000-00-00 00:00:00" OR deactivated_at IS NULL AND role_id =1 AND school_id = (SELECT school_id FROM users WHERE user_id= (int) $this->uri->segment(3));
$query = $this->db->query($sql);
return $query->result();
}

Related

Not getting correct SUM amount for users votes from thread and reply table

I am using codeigniter 3.1.0 and I am trying to get the total SUM of two columns from different tables
If my user_id = 1 it should return the total sum of 421 but returns 431 It is adding the votes from other users on my reply table
Question Using Active Record How can I make sure the SUM is getting the correct amount for the users id.
Model Function
public function thread_reputation($user_id) {
$this->db->select('SUM(reply.votes + thread.votes) AS reputation');
$this->db->from('thread', 'left');
$this->db->join('reply', 'reply.user_id = thread.user_id', 'left');
$this->db->where('thread.user_id', $user_id);
$this->db->where('reply.user_id', $user_id);
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->row();
} else {
return 0;
}
}
Controller section where i echo it
$thread_reputation = $this->thread_analytics_model->thread_reputation('1');
echo $thread_reputation->reputation;
Thread Table
Reply Table
Change your query with this
$query = $this->db->query("SELECT SUM(A.votes) as reputation from
(
SELECT reply.votes FROM reply where reply.user_id = $user_id
UNION ALL
SELECT thread.votes FROM thread where thread.user_id = $user_id
)AS A");
Tested and properly working
Check Screenshot:-
Query using ACTIVE REOCRD
$this->db->select("SUM(A.votes) as reputation");
$this->db->from("(
SELECT reply.votes FROM reply where reply.user_id = $user_id
UNION ALL
SELECT thread.votes FROM thread where thread.user_id = $user_id) AS A");
$query = $this->db->get();
Another Solution using $this->db->get_compiled_select();
public function reputation($user_id) {
$this->db->select('thread.votes');
$this->db->from('thread');
$this->db->where('thread.user_id =' . $user_id);
$thread_query = $this->db->get_compiled_select();
$this->db->select('reply.votes');
$this->db->from('reply');
$this->db->where('reply.user_id ='. $user_id);
$reply_query = $this->db->get_compiled_select();
$query = $this->db->query("SELECT SUM(total.votes) as reputation from ($reply_query UNION ALL $thread_query) as total");
if ($query->num_rows() > 0) {
return $query->row();
} else {
return 0;
}
}
When you will use left join, it will return matched column & all other unmatched column from left table. Use inner join & check your result.

order by clause in codeigniter

I want to fetch the database data by descending order of posted date.Database containing a field named as posted_date. This is my code(in model) for fetch the data.
public function get_data_by_volunteer_id($fields = "*", $volunteer_id)
{
$this->db->select($fields);
$query = $this->db->get_where(self::$tbl_name, array(
"user_id" => $volunteer_id));
return( $query->result() );
}
You can try this
function get_data_by_volunteer_id($fields, $volunteer_id)
{
$query = $this->db->query("SELECT * FROM table_name WHERE user_id = '$volunteer_id' ORDER BY posted_date DESC");
$result = $query->result_array();
return $result;
}
Add following in your query
$this->order_by('posted_date', 'desc');
So your final query would be
$this->db->select($fields);
$this->db->get_where(self::$tbl_name, array(
"user_id" => $volunteer_id));
$this->order_by('posted_date', 'desc');
$query=$this->db->get();
return $query->result();

Codeigniter active query error

Here is my query
$this->db->select('amount AS SavingAmount');
$query = $this->db->get_where('cashman_trial_balance',array('category_id'=>'176','clientId'=>$user['UserID'],'year'=>$year));
On checking in browser its generating this query below
SELECT *, *, `amount` AS SavingAmount FROM (`cashman_trial_balance`) WHERE `category_id` = '176' AND `clientId` = '122' AND `year` = '2015/2016'
I dont know from where the two stars coming from?
Controller code
$som_var = $this->client->statistics();
Model code
function statistics()
{
/* Some other queries */
$b = $this->get_balances();
}
function get_balances()
{
$this->db->select('amount AS SavingAmount');
$query = $this->db->get_where('cashman_trial_balance',array('category_id'=>'176','clientI‌​d'=>$user['UserID'],'year'=>$year));
return $query->result();
}
use this
$query = $this->db->query("SELECT amount AS SavingAmount FROM table_name WHERE category_id = '176'
AND clientId = '$user['UserID']' AND 'year'= '$year') ");
$result = $query->result_array();
return $result;
You can use the simple way
$query = $this->db->query("SELECT amount AS SavingAmount FROM cashman_trial_balance WHERE category_id = '176' AND clientId=$user['UserID'] AND year=$year");

Get the result of SUM and group field from Active record in Codeigniter

I need to build this query in Codeigniter but I don't know how to get the result of the SUM:
SELECT
description, SUM(amount)
FROM
PAYMENT
WHERE
(date_payment between '2014-02-01 00:00:00' AND '2014-02-28 23:59:59')
GROUP BY description;
I'm trying to get the result with this:
$qwer = $this->db->query("
SELECT description, SUM(amount)
FROM PAYMENT
WHERE (date_payment between '$min_date' AND '$max_date')
GROUP BY description;");
$i = 0;
foreach ($qwer->result() as $payment) {
$det_payment[$i] = array(
'description'=>$payment->description,
'amount'=>$payment->amount
);
$i++;
}
Of course "$payment->amount" is wrong, but if I use an alias for the SUM, the model doesn't work.
EDIT: Right now I can choose between the description or the sum, but I can't use both select and select_sum
$this->db->select('description');
//$this->db->select_sum('amount', 'amount');
$this->db->where('date_payment >=', $min_fecha);
$this->db->where('date_payment <=', $max_fecha);
$this->db->group_by("description");
$qwer = $this->db->get('PAYMENT');
Setting FALSE as second parameter, 'select' allows to write a custom sentence.
$this->db->select('description, SUM(amount) AS amount', FALSE);
$this->db->where('date_payment >=', $min_date);
$this->db->where('date_payment <=', $max_date);
$this->db->group_by("description");
$qwer = $this->db->get('PAYMENT');
Documentation for CI2
Documentation for CI3
try something like this:
$query = $this->db->select_sum('amount', 'Amount');
$query = $this->db->where(...)
$query = $this->db->get('payment');
$result = $query->result();
return $result[0]->Amount;

codeigniter active record get last 10 records and sort ASC

I would like to know if this SQL statement is done in Codeigniter active record.
SELECT * FROM (
SELECT *
FROM chat
WHERE (userID = $session AND toID = $friendID)
OR (userID = $friendID AND toID = $session)
ORDER BY id DESC
LIMIT 10
) AS `table` ORDER by id ASC
You have to use the _compile_select() and _reset_select() methods of the active record class.
$this->db->select('*');
$this->db->from('chat');
$this->db->where("(userID='{$session}' AND toID='{$friendID}')");
$this->db->or_where("(userID='{$friendID}' AND toID='{$session}')");
$this->db->order_by('id', 'DESC');
$this->db->limit('10');
$subQuery = $this->db->_compile_select();
$this->db->_reset_select();
$this->db->select('*');
$this->db->from("{$subQuery} AS table");
$this->db->order_by('id', 'ASC');
$query = $this->db->get();
Unfortunately, in CI 2.0+, _compile_select() and _reset_select() are protected methods. Bummer. You'll have to follow this tutorial on extending the DB driver where you can write methods like the following:
function get_compiled_select()
{
return $this->db->_compile_select();
}
function do_reset_select()
{
$this->db->_reset_select();
}
I would like to take the time to point out that this type of action would be better served by joins. You should consider changing your db structure so that joins are possible and efficient.
This will work, though is not the active record variant.
$this->db->query( "SELECT * FROM (
SELECT *
FROM chat
WHERE (userID = ? AND toID = ?)
OR (userID = ? AND toID = ?)
ORDER BY id DESC
LIMIT 10
) AS `table` ORDER by id ASC", array( $session, $friendID, $friendID, $session) );"
You can use query as:
$this->db->select('SELECT *
FROM chat
WHERE (userID = $session AND toID = $friendID)
OR (userID = $friendID AND toID = $session)
ORDER BY id DESC
LIMIT 10') AS `table` ORDER by id ASC', FALSE);

Resources