I need to convert to codeigniter3 active record syntax - sql

I need to join main (4-5) tables and get the latest from the inner join table to get the project current status.
investor have many investments
investments have many investment_details
investment_details has many status through project status
Select
siv.company_name
, siv.full_name
, si.permit_number
, si.project_name
, sid.investment_detailed_id
, sis.project_status_id
, sps.project_status_name
From sma_investors siv
Join sma_investments si
On siv.investor_id = si.investment_id
Join sma_investment_details sid
On si.investment_id = sid.investment_id
Inner Join sma_investment_status sis
On sis.investment_status_id = (
Select investment_status_id
From sma_investment_status s
Where s.investment_detailed_id = sid.investment_detailed_id
Order BY investment_status_id DESC LIMIT 1)
Join sma_project_status sps
On sis.project_status_id = sps.project_status_id
This works fine but I can't convert it the CI3.

There is no advantage to using Query Builder (QB) unless you need parts of the query to be written differently due to some condition. QB is also useful if you want user inputs to be automatically escaped. Otherwise, you simply run a whole lot of extra code that leads to the exact same SQL statement string you already have.
In your case, the sub-select will make the conversion even more difficult to accomplish and add a lot of extra code to be executed.
My advice is to keep it simple and use db->query(), e.g.
$sql = "Select siv.company_name, siv.full_name, si.permit_number, si.project_name
, sid.investment_detailed_id, sis.project_status_id, sps.project_status_name
From sma_investors siv
Join sma_investments si On siv.investor_id = si.investment_id
Join sma_investment_details sid On si.investment_id = sid.investment_id
Inner Join sma_investment_status sis On sis.investment_status_id = (
Select investment_status_id From sma_investment_status s
Where s.investment_detailed_id = sid.investment_detailed_id
Order BY investment_status_id DESC LIMIT 1)
Join sma_project_status sps On sis.project_status_id = sps.project_status_id";
$query = $this->db->query($sql);
if(! $query) // might be false if query fails
{
return null;
}
return $query->row(); // one row of data

I finally come up with my own solution and stick to the QB codding standard and it works as i expected
$q = $this->db->select('*')
->from('investors')
->join('investments', `enter code here`'investors.investor_id=investments.investment_id')
->join('investment_details as sid', 'investments.investment_id=sid.investment_id')
->join('investment_status', 'investment_status.investment_status_id=(select '.$this->db->dbprefix('investment_status').'.investment_status_id from '.$this->db->dbprefix('investment_status').' where '.$this->db->dbprefix('investment_status').'.investment_detailed_id=sid.investment_detailed_id order by '.$this->db->dbprefix('investment_status').'.investment_status_id Desc limit 1)', 'inner')
->join('project_status', 'investment_status.project_status_id=project_status.project_status_id')
->where('sid.company_type_id', 1)
->order_by('investments.investment_id', 'desc')
->limit(5)
->get();

Related

Issue with my Left outer join query

Here are my tables,
I'm trying to fetch the list of free bets with the details if the user has placed his bet or not. This is the query i have written to fetch the details for the same,
select DISTINCT tbl_CreateFreeBet.FreeBetID,
tbl_CreateFreeBet.FreeBetDescription,
tbl_CreateFreeBet.FreeBetAmount,
tbl_CreateFreeBet.TournamentID,
tbl_CreateFreeBet.MatchID,
tbl_UserFreeBets.UserForYes,
tbl_UserFreeBets.UserForNo,
tbl_UserFreeBets.UserForNoBets
from tbl_CreateFreeBet left outer join tbl_UserFreeBets
on tbl_CreateFreeBet.MatchID = 1 and
tbl_CreateFreeBet.MatchID = tbl_UserFreeBets.MatchID and
tbl_CreateFreeBet.FreeBetID = tbl_UserFreeBets.FreeBetID and
tbl_CreateFreeBet.TournamentID = tbl_UserFreeBets.TournamentID and
(tbl_UserFreeBets.UserForYes = 'User2' or tbl_UserFreeBets.UserForNo =
'User2')
This is working fine, when there is a data in tbl_CreateFreeBet table for the MatchID. But if there is no data, then this query is not returning the expected result.
For example: With tbl_CreateFreeBet.MatchID = 1, I need to get all the free bets of matchID = 1, with the details of the passed in user, if has bet on 'yes' or 'no'. This comes up fine, as there is data for MatchId = 1 in tbl_CreateFreeBet.
But, it fails, when the tbl_CreateFreeBet.MatchID = 2 input is passed. Here there is no free bet created for the MatchID = 2. But still it returns me the result for MatchID=1.
Please share the query if one is aware of what changes need to be done for my query. Thank you.
Conditions on the first table in a LEFT JOIN should be in the WHERE clause. I think you intend this logic:
select cfb.FreeBetID, cfb.FreeBetDescription, cfb.FreeBetAmount,
cfb.TournamentID, cfb.MatchID,
ufb.UserForYes, ufb.UserForNo, ufb.UserForNoBets
from tbl_CreateFreeBet cfb left outer join
tbl_UserFreeBets ufb
on cfb.MatchID = ufb.MatchID and
cfb.FreeBetID = ufb.FreeBetID and
cfb.TournamentID = ufb.TournamentID and
(ufb.UserForYes = 'User2' or ufb.UserForNo = 'User2')
where cfb.MatchId = 1

Securing a raw sql query in Laravel to prevent injections

The query when not trying any SQL injection fix works perfectly there is no any connection issue. It is only when trying to change the query to protect it from injections, when the syntax breaks.
I am trying to secure this raw query preventing sql injection
I have seen in the docs (and I know the prepared statements from goo'ol php)
and that Laravel shows a simple example such as this one:
$results = DB::select('select * from users where id = :id', ['id' => 1]);
or this one
$users = DB::select('select * from users where active = ?', [1]);
I am trying to do that where it corresponds, at the WHERE clause equaling the variable provided from the form $a, but all attempts break the syntax.
so anything like:
where author = ?, [$ba], or '$ba' or where author = :ba, ['author' => '$ba']
gives syntax errors.
$ba = 'whatever';
$results =
DB::select(DB::raw("SELECT
t.id, t.AvgStyle, r.RateDesc
FROM (
SELECT
p.id, ROUND(AVG(s.Value)) AS AvgStyle
FROM posts p
INNER JOIN styles s
ON s.post_id = p.id
WHERE author = '$ba'
GROUP BY p.id
) t
INNER JOIN rates r
ON r.digit = t.AvgStyle"
));
Thank you.
Note> question is not eligible for bounties. It is someone always putting it on every question of mine without my permission.
The answer was extremely close to what Everton said: It just needed to go one parentheses to the right.
That is:
, )[$ba]);
You can try this way:
$ba = 'whatever';
$results =
DB::select(DB::raw("SELECT
t.id, t.AvgStyle, r.RateDesc
FROM (
SELECT
p.id, ROUND(AVG(s.Value)) AS AvgStyle
FROM posts p
INNER JOIN styles s
ON s.post_id = p.id
WHERE author = ?
GROUP BY p.id
) t
INNER JOIN rates r
ON r.digit = t.AvgStyle"
, )[$ba]); // #everton We just needed to move it one parentheses
The important thing here is that you need to respect the order if you have others parameters.

The "where" condition worked not as expected ("or" issue)

I have a problem to join thoses 4 tables
Model of my database
I want to count the number of reservations with different sorts (user [mrbs_users.id], room [mrbs_room.room_id], area [mrbs_area.area_id]).
Howewer when I execute this query (for the user (id=1) )
SELECT count(*)
FROM mrbs_users JOIN mrbs_entry ON mrbs_users.name=mrbs_entry.create_by
JOIN mrbs_room ON mrbs_entry.room_id = mrbs_room.id
JOIN mrbs_area ON mrbs_room.area_id = mrbs_area.id
WHERE mrbs_entry.start_time BETWEEN "145811700" and "1463985000"
or
mrbs_entry.end_time BETWEEN "1458120600" and "1463992200" and mrbs_users.id = 1
The result is the total number of reservations of every user, not just the user who has the id = 1.
So if anyone could help me.. Thanks in advance.
Use parentheses in the where clause whenever you have more than one condition. Your where is parsed as:
WHERE (mrbs_entry.start_time BETWEEN "145811700" and "1463985000" ) or
(mrbs_entry.end_time BETWEEN "1458120600" and "1463992200" and
mrbs_users.id = 1
)
Presumably, you intend:
WHERE (mrbs_entry.start_time BETWEEN 145811700 and 1463985000 or
mrbs_entry.end_time BETWEEN 1458120600 and 1463992200
) and
mrbs_users.id = 1
Also, I removed the quotes around the string constants. It is bad practice to mix data types, and in some databases, the conversion between types can make the query less efficient.
The problem you've faced caused by the incorrect condition WHERE.
So, should be:
WHERE (mrbs_entry.start_time BETWEEN 145811700 AND 1463985000 )
OR
(mrbs_entry.end_time BETWEEN 1458120600 AND 1463992200 AND mrbs_users.id = 1)
Moreover, when you use only INNER JOIN (JOIN) then it be better to avoid WHERE clause, because the ON clause is executed before the WHERE clause, so criteria there would perform faster.
Your query in this case should be like this:
SELECT COUNT(*)
FROM mrbs_users
JOIN mrbs_entry ON mrbs_users.name=mrbs_entry.create_by
JOIN mrbs_room ON mrbs_entry.room_id = mrbs_room.id
AND
(mrbs_entry.start_time BETWEEN 145811700 AND 1463985000
OR ( mrbs_entry.end_time BETWEEN 1458120600 AND 1463992200 AND mrbs_users.id = 1)
)
JOIN mrbs_area ON mrbs_room.area_id = mrbs_area.id

DISTINCT SQL query with inner joins that omits a column from considerations,

I have a DB2 query as follows:
SELECT DISTINCT RETAILMASTERFILE.DOIDCD AS "RETAILMASTERFILE_DOIDCD",
RETAILMASTERFILE.COCOMO AS "RETAILMASTERFILE_COCOMO",
#XENOS.CUSTREF AS "XENOS_CUSTREF",
#XENOS.ADDUDT AS "XENOS_ADDUDT",
#XENOS.ADUPDD AS "XENOS_ADUPDD",
#XENOS.ADUPDT AS "XENOS_ADUPDT",
#XENOS.ADSTAT AS "XENOS_ADSTAT"
FROM RETAILMASTERFILE INNER JOIN
#XENOS ON RETAILMASTERFILE.DOCOMP = #XENOS.ADCOMP
AND RETAILMASTERFILE.COCOMO = #XENOS.ADDELN
WHERE (RETAILMASTERFILE.DOIDCD = 'CUST008')
AND (RETAILMASTERFILE.COCOMO = '345126032')
AND (RETAILMASTERFILE.DOCOMP = 'LONDON')
The problem is #XENOS.ADUPDT may not be unique which gives me an unwanted duplicate record.
Is there any way I can exclude this from consideration ? Everything I've tried so far within my limited knowledge and crude understanding of group by has so far broken my query.
Use GROUP BY instead:
SELECT RETAILMASTERFILE.DOIDCD AS "RETAILMASTERFILE_DOIDCD",
RETAILMASTERFILE.COCOMO AS "RETAILMASTERFILE_COCOMO",
#XENOS.CUSTREF AS "XENOS_CUSTREF",
#XENOS.ADDUDT AS "XENOS_ADDUDT",
#XENOS.ADUPDD AS "XENOS_ADUPDD",
MAX(#XENOS.ADUPDT) AS "XENOS_ADUPDT",
#XENOS.ADSTAT AS "XENOS_ADSTAT"
FROM RETAILMASTERFILE INNER JOIN
#XENOS
ON RETAILMASTERFILE.DOCOMP = #XENOS.ADCOMP AND
RETAILMASTERFILE.COCOMO = #XENOS.ADDELN
WHERE (RETAILMASTERFILE.DOIDCD = 'CUST008') AND (RETAILMASTERFILE.COCOMO = '345126032') AND
(RETAILMASTERFILE.DOCOMP = 'LONDON')
GROUP BY RETAILMASTERFILE.DOIDCD,
RETAILMASTERFILE.COCOMO,
#XENOS.CUSTREF,
#XENOS.ADDUDT,
#XENOS.ADUPDD,
#XENOS.ADSTAT;

Problem with adding custom sql to finder condition

I am trying to add the following custom sql to a finder condition and there is something not quite right.. I am not an sql expert but had this worked out with a friend who is..(yet they are not familiar with rubyonrails or activerecord or finder)
status_search = "select p.*
from policies p
where exists
(select 0 from status_changes sc
where sc.policy_id = p.id
and sc.status_id = '"+search[:status_id].to_s+"'
and sc.created_at between "+status_date_start.to_s+" and "+status_date_end.to_s+")
or exists
(select 0 from status_changes sc
where sc.created_at =
(select max(sc2.created_at)
from status_changes sc2
where sc2.policy_id = p.id
and sc2.created_at < "+status_date_start.to_s+")
and sc.status_id = '"+search[:status_id].to_s+"'
and sc.policy_id = p.id)" unless search[:status_id].blank?
My find statement:
Policy.find(:all,:include=>[{:client=>[:agent,:source_id,:source_code]},{:status_changes=>:status}],
:conditions=>[status_search])
and I am getting this error message in my log:
ActiveRecord::StatementInvalid (Mysql::Error: Operand should contain 1 column(s): SELECT DISTINCT `policies`.id FROM `policies` LEFT OUTER JOIN `clients` ON `clients`.id = `policies`.client_id WHERE ((((policies.created_at BETWEEN '2009-01-01' AND '2009-03-10' OR policies.created_at = '2009-01-01' OR policies.created_at = '2009-03-10')))) AND (select p.*
from policies p
where exists
(select 0 from status_changes sc
where sc.policy_id = p.id
and sc.status_id = '2'
and sc.created_at between 2009-03-10 and 2009-03-10)
or exists
(select 0 from status_changes sc
where sc.created_at =
(select max(sc2.created_at)
from status_changes sc2
where sc2.policy_id = p.id
and sc2.created_at < 2009-03-10)
and sc.status_id = '2'
and sc.policy_id = p.id)) ORDER BY clients.created_at DESC LIMIT 0, 25):
what is the major malfunction here - why is it complaining about the columns?
The conditions modifier is expecting a condition (e.g. a boolean expression that could go in a where clause) and you are passing it an entire query (a select statement).
It looks as if you are trying to do too much in one go here, and should break it down into smaller steps. A few suggestions:
use the query with find_by_sql and don't mess with the conditions.
use the rails finders and filter the records in the rails code
Also, note that constructing a query this way isn't secure if the values like status_date_start can come from users. Look up "sql injection attacks" to see what the problem is, and read the rails documentation & examples for find_by_sql to see how to avoid them.
Ok, I've managed to retool this so it is more friendly to a conditions modifier and I think it is doing the sql query correctly.. however, it is returning policies that when I try to list the current status (the policy.status_change.last.status) it is set to the same status used in the query - which is not correct
here is my updated condition string..
status_search = "status_changes.created_at between ? and ? and status_changes.status_id = ?) or
(status_changes.created_at = (SELECT MAX(sc2.created_at) FROM status_changes sc2
WHERE sc2.policy_id = policies.id and sc2.created_at < ?) and status_changes.status_id = ?"
is there something obvious to this that is not returning all of the remaining associated status changes once it finds the one in the query?
here is the updated find..
Policy.find(:all,:include=>[{:client=>[:agent,:source_id,:source_code]},:status_changes],
:conditions=>[status_search,status_date_start,status_date_end,search[:status_id].to_s,status_date_start,search[:status_id].to_s])