i am using codeigniter active records to execute a simple mysql query to select data in last one hour.
so my query is:
SELECT * FROM tablename WHERE added_datetime >= DATE_SUB(NOW(),INTERVAL 1 HOUR)
and my codeigniter code to form this query is:
$data=array(
'added_datetime >='=>'DATE_SUB(NOW(),INTERVAL 1 HOUR)',
);
$query=$this->db->get_where('tablename',$data);
now the issue is codeigniter adds a single quotes around the DATE_SUB function and due to this the query not works on mysql server.
codeigniter produces:
SELECT * FROM (`tablename`) WHERE `added_datetime` >= 'DATE_SUB(NOW(),INTERVAL 1 HOUR)'
i also tried by adding FALSE as 3rd parameter in get_where but stil not worked
$query=$this->db->get_where('tablename',$data,FALSE);
it also produced the same query as above.
So please suggest me how to solve this issue.
-Thanks
Try doing something like this instead:
$this->db->where("added_datetime >= DATE_SUB(NOW(),INTERVAL 1 HOUR)", NULL, FALSE);
$query = $this->db->get('tablename');
$this->db->get_where(); doesn't provide the function to unescaping your where clause.
Related
I'm executing a PHP yii2 query to get records from the database but it's not working. But I directly executed the query in the MYSQL console then it gives me the expected output.
Normal SQL
SELECT * FROM `tbl_inbox` WHERE sender_id=778 AND recipient_id=736 OR sender_id=778 AND recipient_id=736 ORDER BY timestamp DESC LIMIT 1
Above query giving me expected result but when i change to Yii2 like :
$message=Inbox::find()->select(['message'])->where(['sender_id'=>$sender_id,'recipient_id'=>$recipient_id])->orWhere(['sender_id'=>$recipient_id,'recipient_id'=>$sender_id])->andWhere(['ad_id'=>$ad_id,'category'=>$category])->orderBy(['timestamp'=>SORT_DESC])->one();
It gives me the wrong result.
What is my logic :
I have a chat on my website and I need to get the last message order by timestamp. But sender_id and the recipient will be visa versa.
How to fix ?
There are significant differences between the normal SQL version of the query and the Yii version.
1) Selected fields
The normal SQL query selects all fields, but Yii version selects only message field.
This is because the normal SQL has SELECT * FROM ... but in Yii query you are calling select(['message']). If you want to select all fields you can leave the select() method call out or you can use select('*').
2) Your conditions are different
Considering operator priority your conditions in normal SQL are:
(sender_id=778 AND recipient_id=736)
OR (sender_id=778 AND recipient_id=736)
But in your Yii version of query:
(
(sender_id=778 AND recipient_id=736)
OR (sender_id=736 AND recipient_id=778)
) AND (
ad_id=$ad_id AND category=$category
)
In your normal SQL the both sides of OR condition are same but in your Yii version the values for sender/recipient are swapped in the second argument of OR operator.
Also there is extra part added by this call andWhere(['ad_id'=>$ad_id,'category'=>$category])
$message=Inbox::find()->select(['message'])->where(['sender_id'=>$sender_id,'recipient_id'=>$recipient_id])->orWhere(['sender_id'=>$recipient_id])->orWhere(['recipient_id'=>$sender_id])->andWhere(['ad_id'=>$ad_id,'category'=>$category])->orderBy(['timestamp'=>SORT_DESC])->one();
try this
I'm getting following sql
SELECT `message` FROM `user` WHERE ((((`sender_id`='2333') AND (`recipient_id`='23222')) OR (`sender_id`='23222')) OR (`recipient_id`='23333')) AND ((`ad_id`='10') AND (`category`='1')) ORDER BY `timestamp` DESC
you can check raw sql easily, then it will be mostly straight forward how Yii Query builder works.
use following code:
$rawSql = Inbox::find()
...
->createCommand()->getRawSql();
I would change your code into this:
$message=Inbox::find()
->select(['message'])
->where([
'and',
[
'or',
['sender_id'=>$sender_id,'recipient_id'=>$recipient_id],
['sender_id'=>$recipient_id,'recipient_id'=>$sender_id]
],
['ad_id'=>$ad_id,'category'=>$category]
])
->orderBy(['timestamp'=>SORT_DESC])->one();
I worked on a Codeigniter 2 project, there I have an active record like:
$query = $this->db->select_sum('Cardit * GPA', 'sum')
->get('marks_info');
It generates query like:
SELECT SUM(`Cardit` * `GPA`) AS `sum` FROM `marks_info`
Recently I migrated my project to Codeigniter 3, but the same active record generated little different query like:
SELECT SUM(`Cardit *` `GPA`) AS `sum` FROM `marks_info`
that is wrong, it includes * with Cardit ('Cardit *') in SUM section.
Difference:
Can anybody tell me, how can I solve this issue in CodeIgniter 3 ?
Try this, It will give you your expected output
$query = $this->db->select('sum(Cardit * GPA) sum')->get('marks_info');
To avoid backticks within the query. You can assign false to protect_identifiers like :
$this->db->_protect_identifiers=false;
and run your query accordingly.
I'm trying to run this query with Codeigniter:
SELECT * FROM `bf_bs_history` WHERE date > DATE_SUB(now(), INTERVAL 2 MONTH)
If I enter it directly in phpMyAdmin, I get the result I want. However, running if from the code, it will not take any effect. It's not filtering at all.
The PHP line looks like this:
$this->history_model->where(array('date > ' => 'DATE_SUB(now(), INTERVAL 2 MONTH)'))->find_all();
Any idea where I go wrong?
CodeIgniter Active Record is adding backticks to your statement, which renders your clause as a string, not an executable function. You can set a second parameter to false to stop that. Also, for a function predicate like this you can simply pass in the string:
$this->history_model->where("date > DATE_SUB(now(), INTERVAL 2 MONTH)", false)->find_all();
Using the following table "technotes":
And, using the following SQLi Query:
SELECT *
FROM
`technotes`
WHERE
`techgroup` LIKE '%dispatch%' OR
`techgroup` LIKE '%30243542%' AND
`expires` >= '2014-12-18' AND
`viewed` NOT LIKE '%30243542%'
What was expected was that alertid's: 23324325 & 23546576 (1st and last one) would be returned. But instead i am getting record 1,3,4,5 being returned. I am missing something in the order of operation or some other component in the SQLi select statement is malformed but not sure what. Can someone advise what I have left out or need to change so this works properly?
Try this:
SELECT * FROM
`technotes`
WHERE
(`techgroup` LIKE '%dispatch%' OR `techgroup` LIKE '%30243542%')
AND `expires` >= '2014-12-18'
AND (`viewed` NOT LIKE '%30243542%' OR ISNULL(`viewed`) )
I have a complex MSSQL query with multiple joins. When I query using SQL Query Analyzer, it returns results after consuming about 5 minutes. However, when I query using PHP mssql_query() function, it returns an error mssql_query() failed with no useful information.
Followings are the analysis of this problem so far.
Response time limit of php server is not a problem. Time limit is set to infinite. In fact, this same query returns results after about 30 seconds on different production servers.
I tried using mssql_get_last_message() to get more details on why it failed. But so far, no luck. All I get is "Changed database context to 'dbsdb'", where 'dbsdb' is the name of database I am querying.
This is the query I am using, if that matters.
SELECT L.[strStation], L.[nEntitlement1], L.[nEntitlement2], O.nOrders,
L.[nEntitlement3], L.[nEntitlement4], S.[strFirm], S.[nStatus],
S.[nFeatures], S.[nFeatures2], S.[nFeatures3], S.[strDescription]
FROM [tblLogin] AS L
LEFT JOIN [tblStation] AS S ON L.[strStation] = S.[strStation]
LEFT JOIN (
SELECT [strStation], COUNT(DISTINCT(nRecordId)) as nOrders
FROM [tblOrder]
WHERE [timeOrderDate] >= '2013-06-04' AND
[timeOrderDate] <= '2013-06-28'
GROUP BY strStation
) AS O ON O.[strStation] = S.[strStation]
WHERE L.[timeLoginTime] >= '2013-06-04 00:00:00' AND
L.[timeLoginTime] <= '2013-06-28 23:59:59' AND
S.[strFirm] in ('FIRMA','FIRMB')
This is the code that I use to query.
$link = mssql_connect('192.168.251.90', 'sa', '');
if (!mssql_select_db('dbsdb', $link))
var_dump(mssql_get_last_message());
$query = mssql_query($sql, $link);
EDIT I
I narrowed down to one spot. When I remove O.nOrders part from the SELECT clause, the query works perfectly fine.
But WHY???
EDIT II
This is driving me crazy. Query works sometimes even with O.nOrders part in SELECT clause. This seems totally random to me, but I know there is no such thing as real random in this world...there should be a reason...