MySQLi join using date(now()) in where clause - php

I am running this query in phpmyadmin and it works fine. But on running it in joshcam's MySQLi Database class it gets wrong data
Query:
SELECT
s.az
, s.ta
, s.zamanSarfShode
, p.name
FROM
saateruzane s
JOIN
projhe p
JOIN
kareruzane k
WHERE
s.ProjheId = p.id
AND
k.id = s.ruzId
AND
k.ruzGregorian = date(now())
PHP code :
$con->join('projhe p', 's.ProjheId = p.id');
$con->join('kareruzane k', 'k.id = s.ruzId');
$con->joinWhere('kareruzane k','k.ruzGregorian', 'date(now())');
$tines = $con->get('saateruzane s',null,'s.az ,s.ta ,s.zamanSarfShode ,p.name');

The definition for joinWhere is
public function joinWhere($whereJoin, $whereProp, $whereValue = 'DBNULL', $operator = '=', $cond = 'AND')
So you don't need to pass in every part. Instead, try this:
$con->joinWhere('kareruzane k','k.ruzGregorian = date(now())');
Though better than date(now()) is CURDATE()
$con->joinWhere('kareruzane k','k.ruzGregorian = curdate()');
However, I'm not sure you should be using a join here, since it's part of the WHERE clause on your original query, not the JOIN clause. So instead do
$con->where('k.ruzGregorian = curdate()');

With just a fast look on this lib docs, I found this:
'createdAt' => $db->now(),
// createdAt = NOW()
https://github.com/joshcam/PHP-MySQLi-Database-Class#insert-query
In your case try use
$con->joinWhere('kareruzane k','k.ruzGregorian', $con->now());

Related

Yii2 translating findBySql query to QueryBuilder query

I have the following query using findbysql:
$query = Users::findBySql('select a.user_id, a.last_name,a.first_name, a.emp_id, ar.role_id from auth_users a, auth_user_roles AR, AUTH_USER_DEPTS AD, DEPARTMENTS D
where AD.DEPT_ID = D.DEPT_ID AND AR.USER_ID = AD.USER_ID and a.user_id = ar.user_id
AND D.DEPT_GROUP_ID = :dept_group_id AND (ACCESS_END_DATE > SYSDATE OR ACCESS_END_DATE IS NULL)
UNION
SELECT DISTINCT a.user_id, a.last_name, a.first_name, a.emp_id, NULL AS role_id FROM auth_users a, AUTH_USER_ROLES AR, AUTH_USER_DEPTS AD, DEPARTMENTS D
WHERE AD.DEPT_ID = D.DEPT_ID AND AR.USER_ID = AD.USER_ID and a.user_id = ar.user_id
AND D.DEPT_GROUP_ID = :dept_group_id AND
AR.ACCESS_END_DATE < SYSDATE AND AR.USER_ID NOT IN (select USER_ID from auth_user_roles where ACCESS_END_DATE > SYSDATE OR ACCESS_END_DATE IS NULL)', [':dept_group_id' => $dept_group_id ]);
This query does exactly what I want it to, but the problem is when I try to put it into a gridview it does not sort. According to Sort and search column when I'm querying with findbysql in yii2 it seems like I need to use query builder instead.
So I was trying to do that with the first part of my query (before the union), and it looks like so:
$query1 = (new \yii\db\Query())
->select(['user_id', 'last_name', 'first_name', 'emp_id'])
->from('AUTH_USERS');
$query2 = (new \yii\db\Query())
->select('USER_ID')
->from('AUTH_USER_ROLES')
->where('ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL');
$query = $query1->innerJoin('AUTH_USER_DEPTS', 'AUTH_USER_DEPTS.user_id = AUTH_USERS.user_id')->innerJoin('DEPARTMENTS', 'AUTH_USER_DEPTS.dept_id = DEPARTMENTS.dept_id');
$query->innerJoin('AUTH_USER_ROLES', 'AUTH_USER_ROLES.USER_ID = auth_users.USER_ID')->where('ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL');
However, my query comes out like this in yii and apparently oracle is not accepting the double quotes around the column names:
SELECT "user_id", "last_name", "first_name", "emp_id" FROM "AUTH_USERS"
INNER JOIN "AUTH_USER_DEPTS" ON AUTH_USER_DEPTS.user_id = AUTH_USERS.user_id
INNER JOIN "DEPARTMENTS" ON AUTH_USER_DEPTS.dept_id = DEPARTMENTS.dept_id
INNER JOIN "AUTH_USER_ROLES" ON AUTH_USER_ROLES.USER_ID = auth_users.USER_ID
WHERE ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL
I know the query might be incorrect here already but I cant even get the double quotes to go away. Tried defining the select statements multiple ways suggested by the yii docs already with no success:
select(['user_id', 'last_name', 'first_name', 'emp_id'])
select('user_id', 'last_name', 'first_name', 'emp_id')
select("user_id, last_name,first_name,emp_id")
I have also tried joining the queries like this from the docs: http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html
$query = $query1->innerJoin(['u' => $query2], 'u.user_id = user_id');
but it also complains that it doesnèt recognize u and the query instead comes out like so in yii:
SELECT COUNT(*) FROM "AUTH_USERS" INNER JOIN "AUTH_USER_DEPTS" ON AUTH_USER_DEPTS.user_id = AUTH_USERS.user_id INNER JOIN "DEPARTMENTS" ON AUTH_USER_DEPTS.dept_id = DEPARTMENTS.dept_id INNER JOIN (SELECT "USER_ID" FROM "AUTH_USER_ROLES" WHERE ACCESS_END_DATE>SYSDATE OR ACCESS_END_DATE IS NULL) "u" ON u.user_id = auth_users.user_id
At this point im just looking for the easiest way to build this query (whether it be using querybuilder or some other way) so that I can pass the query to my gridview and sort it.
I would recommend you first create all the data models you need from the tables you need for the query, using Gii it should be easy and it even creates the relationships you will need.
After that, you can do something like the following:
$query = Users::find()
->joinWith('theRelation1Name')
->joinWith('theRelation2Name')
->joinWith('theRelation3Name')
...
This way you don't need to give tables aliases or add the conditions needed for the relations to work.

Codeigniter Subquery

I have this query can someone help me transfer it to codeigniter style in model.
SELECT
a.*,
(
SELECT COUNT(*) FROM `comment` c
WHERE c.comment_article_id = a.`News_News_ID`
) AS counta
FROM
`news_news` a
Update:
I try this and it work nicely but im not sure it is good practice
$sql="SELECT a.*,
( SELECT COUNT(*) FROM comment c WHERE c.comment_article_id = a.`News_News_ID` ) as counta
FROM `news_news` a";
$query = $this->db->query($sql, array('News_Cate_ID' => $cate), $start, $display);
Use join instead of sub query and according to your query you didn't need where condition while using joins
$this->db->select('a.*,COUNT(c.*) AS counta');
$this->db->from('news_news AS a');
$this->db->join('comment AS c', 'c.comment_article_id = a.News_News_ID');
$query = $this->db->get();
For more information
Try below code. This query will return each article with comment count
$this->db->select('a.*,COUNT(c.*) AS count');
$this->db->from('news_news a');
$this->db->join('comment c', 'a.News_News_ID = c.comment_article_id ','LEFT');
$this->db->group_by('a.News_News_ID')
$query = $this->db->get();

Zend Update Query

How to write below mysql query using zend syntax?
UPDATE core_user_transaction as t
JOIN core_user_transaction_therapy AS cuts ON cuts.tid=t.tid
JOIN therapy_booking AS tb ON cuts.conf_id = tb.conf_id
JOIN therapy_service_fees AS fees ON cuts.fee_id=fees.id
JOIN therapy_service_taxes AS tst ON fees.service_id=tst.service_id
JOIN core_tax AS ct ON ct.tax_id = tst.tax_id
SET t.tax=ROUND(t.fee*(ct.tax_value/100),2),
t.amount = (ROUND(t.fee*(ct.tax_value/100),2)+t.fee)
WHERE tb.datetime >= '2015-10-01 00:00:00'
AND t.state = 'PENDING'
AND t.status ='ACTIVE'
Try this:
$adapter = new Zend\Db\Adapter\Adapter($driverConfig);
$sql = "YOUR_QUERY";
$statement = $adapter->query($sql);
$statement->execute();
Also please refer Zend\Db\Adapter
There is no possible with the 'update()' method provided by the Zend Db Adapter.
You can however, run the query manually using the adapter. Something like:
// $adapter is an instance of Zend_Db_Adapter
$adapter->query(YOUR QUERY HERE);

Convert complex JOIN query in codeigniter

I'm converting my existing website to CI, and I have been trying for several days to convert this query to CI-friendly code:
$result = mysql_query("
SELECT t1.mnumber, t1.mcontent, t1.mcontact
FROM sms t1
JOIN (
SELECT mContent,mcontact, mnumber, MAX(mID) mID
FROM sms
GROUP BY mContact
) t2 ON t1.mcontact = t2.mcontact AND t1.mid = t2.mid
GROUP BY t1.mContact
ORDER BY t1.mid DESC
");
But no matter what I try, I can't get the correct result on CI.
I hope you guys can help me out here!
The closest to a result that i did get, was when i used the subquery hack.
However, out of frustration i deleted the block of code and kept trying.
I decided to use a flat query, like the one posted above. This almost gives me results.
$query = $this->db->query("SELECT t1.mnumber, t1.mcontent, t1.mcontact FROM sms t1
JOIN (SELECT mContent,mcontact, mnumber, MAX(mID) mID FROM sms GROUP BY mContact) t2
ON t1.mcontact = t2.mcontact AND t1.mid = t2.mid GROUP BY t1.mContact ORDER BY t1.mid DESC");
$contacts = array();
//Add data to our array
foreach($query->result() as $row){
echo $row->mNumber;
}
return $contacts;
However, in my view i get the notice "Message: Undefined property: stdClass::$mNumber"
So still no results, plus i prefer the CI query method.
You can use it in codeigniter like this
$query = " SELECT t1.mnumber, t1.mcontent, t1.mcontact
FROM sms t1
JOIN (
SELECT mContent,mcontact, mnumber, MAX(mID) mID
FROM sms
GROUP BY mContact
) t2 ON t1.mcontact = t2.mcontact AND t1.mid = t2.mid
GROUP BY t1.mContact
ORDER BY t1.mid DESC";
$result = $this->db->query($query);
return $result->result();
2nd Method
You can use sub query way of codeigniter to do this for this purpose you
will have to hack codeigniter. like this. Go to system/database/DB_active_rec.php
Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now subquery writing in available And now here is your query with active record
$select = array(
'mContent',
'mcontact',
'mnumber',
'MAX(mID) mID'
);
$this->db->select($select);
$this->db->from('sms');
$this->db->group_by('mContact');
$subquery = $this->db->_compile_select(); // get the query string
$this->db->_reset_select(); // reset so it can newly form the query
unset($select);
$select = array(
't1.mnumber',
't1.mcontent',
't1.mcontact'
);
$this->db->select($select);
$this->db->join('',"($subquery)");
$this->db->from('sms t1');
$this->db->group_by('t1.mContact');
$this->db->order_by('t1.mid','DESC');
$result = $this->db->get();
return $result->result();
And the thing is done. Cheers!!!
Note : While using sub queries you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Er, shouldn't that be (at a guess)...
SELECT t1.mnumber
, t1.mcontent
, t1.mcontact
, t1.mid
FROM sms t1
JOIN
( SELECT mcontact
, MAX(mID) mID
FROM sms
GROUP BY mContact
) t2
ON t1.mcontact = t2.mcontact
AND t1.mid = t2.mid
ORDER
BY t1.mid DESC;
This may not fully answer your question, but for those of you who are Googling for a "JOIN AND" (so that you can AND some extra stuff on the Join, before the WHERE clause kicks in), here's a hacky way to do it:
$this->db->join('table_to_join', 'first_table.connect_id = table_to_join.id AND table_to_join.some_filter != 0');
Definitely not pretty, but that obviously forces the AND to occur immediately after the JOIN, before you get into the WHERE stuff for the rest of your query on first_table
Well, its easy to implement in CI version 3+
$subQuery = $this->db->select( 'table2.*' )
->join( 'table3', 'table3.orderId = table2.fkOrderId', 'INNER' )
->where()->get_compiled_select( 'table2' );
$this->db->select( 'table1.*' )
->join( '(' . $subQuery . ') AS b', 'b.`fkCouponId` = table1.couponId', 'LEFT', FALSE )
->get( 'table1' )
TIP: Make sure you don't use any query builder methods above the subquery part.

How to write a LEFT JOIN in a DELETE QUERY?

Will you give me an example of a delete query that use a left join using Doctrine?
It's not possible. See that: http://trac.doctrine-project.org/ticket/2142
You have to use a subquery in the where clause: http://www.doctrine-project.org/documentation/manual/1_2/en/dql-doctrine-query-language:subqueries
Try something like that:
$q = Doctrine_Query::create()
->delete('TableB b')
->where('b.id NOT IN (SELECT b.id FROM TableB b \
INNER JOIN b.TableA a WHERE b.date > NOW() AND a.channel_id = 10)')
->execute();
Its not necessary to write the query in plain sql, you can still use the QueryBuilder for that:
$entityManager = $this->getEntityManager();
$queryBuilder = $entityManager->createQueryBuilder();
$subQueryCityDataSources = $queryBuilder->getEntityManager()->createQueryBuilder()
->select('cds')
->from(CityDataSource::class, 'cds')
->where('cds.dataSource = :dataSource')
;
$queryBuilder->delete($entityClass, 'd');
$queryBuilder->where($queryBuilder->expr()->in('d.cityDataSource', $subQueryCityDataSources->getDQL()));
$queryBuilder->setParameter('dataSource', $dataSource);
$query = $queryBuilder->getQuery();
$query->execute();
This generates this query:
DELETE
AppBundle\Entity\ConcreteData\News d
WHERE
d.cityDataSource IN
(
SELECT
cds
FROM
AppBundle\Entity\CityDataSource cds
WHERE
cds.dataSource = :dataSource
)
Important note: you have to append all the parameters in the outer query.

Categories