how to execute mysql raw query in drupal - drupal

SELECT SUM(visits) AS totalvisits
FROM (SELECT visits FROM dip_website_visits WHERE nid=20339 ORDER BY date DESC LIMIT 12) AS T
How to convert this SQL query to Drupal query? Can we use db_query for this?

You can convert it to Drupal query like this:
$subquery = \Drupal::database()->select('dip_website_visits');
$subquery->addField('dip_website_visits', 'visits');
$subquery->condition('nid', 20339);
$subquery->orderBy('date', 'desc');
$subquery->range(0, 12);
$query = \Drupal::database()->select($subquery);
$query->addExpression('sum(visits)', 'totalvisits');
$results = $query->execute()->fetchAssoc();

Related

Doctrine Native query inside query builder join

I am working on a query on Doctrine 2 (with Symfony 2.8)
I have this query giving me relevant info:
$qb = $this->createQueryBuilder('ea');
$qb->join('ea.entity_b', 'eb')
->join('ea.entity_c', 'ec')
->join('ec.entity_d', 'ed')
->join('MainBundle:Entity_E', 'ee','WITH', 'ee.column1 = ea.id')
->join('MainBundle:Entity_F', 'ef', 'WITH', 'ea.column1 = ef.id');
Now, I need to add extra info to that query, but it comes from a native SQL, something like this:
SELECT * FROM DS ORDER BY id DESC LIMIT 1
And make sure that the id of the result from the native query is equal to ef.id
I hope I made any sense.
Thanks
Do you know DQL ?
Similar to SQL but adapted for Doctrine.
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/dql-doctrine-query-language.html
You can then do queries like :
<?php
$query = $em->createQuery("SELECT u FROM User u JOIN u.address a WHERE a.city = 'Berlin'");
$users = $query->getResult();

Doctrine2 "order by" before "group by"

I know that similar question was asked 3 years ago (Doctrine2 Order By before Group By) but maybe from that time something changed.
i have 2 entity propertes:
orderId
orderUpdateDate
both as a pair are set to be unique, but for listing I need last update date so sorting should be
order by orderUpdateDate DESC
and then grouped by orderId so I have orders only once.
group by orderId
problem is such that when I paste both in one query in query builder I got random listing of orders
To achieve such a result you'd have to end up with following SQL query:
SELECT n.id, n.update_date
FROM (
SELECT o.id, o.update_date
FROM orders o
ORDER BY o.update_date DESC
) n
GROUP BY n.id;
Unfortunately Doctrine's DQL doesn't support nested queries in FROM clause. However, it allows you to create a custom, native SQL query that can be mapped by ORM:
$rsm = new ResultSetMappingBuilder($em);
$rsm->addRootEntityFromClassMetadata('MyProject\\Order', 'o');
$sql = sprintf('SELECT %s FROM (SELECT ...) GROUP BY ...', $rsm->generateSelectClause());
$query = $em->createNativeQuery($sql, $rsm);
$result = $query->getResult();

query 2 wordpress database tables at once

I have the following query which i am running:
$query = "SELECT post_title, ID, post_date_gmt, post_author
FROM wp_posts
WHERE post_type='course-manager'
AND post_status='publish'
AND SUBSTRING(post_date_gmt,1,4) = '$this->yearGet'
AND SUBSTRING(post_date_gmt,6,2) = '$this->monthGet'
AND post_author = '$userid'
ORDER BY post_title";
$query_result = mysql_query ($query);
while ($info = mysql_fetch_array($query_result))
{
currently this is querying just the wordpress posts table. i would like to also query data from the wordpress postmeta table, an example would be like this where i have added the "AND course_date which is within the postmeta table:
$query = "SELECT post_title, ID, post_date_gmt, post_author
FROM wp_posts
WHERE post_type='course-manager'
AND post_status='publish'
AND SUBSTRING(post_date_gmt,1,4) = '$this->yearGet'
AND SUBSTRING(post_date_gmt,6,2) = '$this->monthGet'
AND post_author = '$userid'
AND course_date = '$this->yearGet'
ORDER BY post_title";
$query_result = mysql_query ($query);
while ($info = mysql_fetch_array($query_result))
{
any help would be greatly appreciated
If you need to query a combined set of data whose source is from more than one table, you need to do a join. Basically, you need to make the connection between the 2 tables, in the post and postmeta case, that connection would be the post id. So the query should look like this:
SELECT a.something, b.anotherthing
FROM wp_posts AS a JOIN wp_postmeta AS b
ON a.ID = b.post_id
//followed by all of your where clause...

Getting the last item from a Drupal db_fetch_object

What's the best way to do this? I've been falling back onto doing a while() loop over the result and snagging the last one as it goes by, but this seems a little, um, inelegant. D7 offers some help here, but is there any advice out there for D6? Thanks!
Why not reverse the order of your query and limit to 1 and get that?
Something like:
$result = db_query_range("SELECT * FROM {table} ORDER BY field DESC", 0, 1);
http://api.drupal.org/api/drupal/includes--database.mysql.inc/function/db_query_range/6
In general case (no engine tips like for mysql), use:
$query = 'SELECT nid, title from {node} WHERE type="page"';
$query_count = 'SELECT count(*) from {node} WHERE type="page"';
$count = db_result(db_query($query_count)); // $query_count
$last_record = db_fetch_object(db_query_range($query, $count-1, 1));
If query use ordering, just use "counter-ordering":
$query = 'SELECT nid, title from {node} WHERE type="page" ORDER BY nid ASC';
// ...
$counterquery = 'SELECT nid, title from {node} WHERE type="page" ORDER BY nid DESC LIMIT 0,1';
$last_record = db_fetch_object(db_query($counterquery));
Try to use db_last_insert_id()

Help me with this COUNT query for a php file

$query = 'SELECT COUNT(*) FROM Security WHERE ips=$currentip';
How do i get this to count the $currentip values that i make the variable equal to.
assuming you're using the mysqli function set:
$mysqli=new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$query = 'SELECT COUNT(*) as num FROM Security WHERE ips=$currentip';
$response=$mysqli->query($query);
$row=$response->fetch_assoc();
$count=$row['num'];
It would be preferable to clean $currentip. Or even better to use a prepared statement.

Resources