Convert SQL query into Drupal 7 PHP rules - drupal

SELECT address
FROM user_address
WHERE username = '$user->name'
ORDER BY time DESC
LIMIT 1
Here is the SQL query that I can understand. How is it possible to convert it into Drupal's 7 PHP? I'm trying to figure that out for a day, and I tried different approaches, but it seems that I am just bad in that.

You can use db_select :
$results = db_select('user_address', 'ua')
->fields('ua', array('address'))
->condition('ua.username', $user->name, '=')
->orderBy('ua.time', 'DESC')
->range(0,1)
->execute()
->fetchAll();
var_dump($results);
Otherwise you can use db_query if you want to write entire SQL :
$results = db_query("SELECT address
FROM user_address
WHERE username = :username
ORDER BY time DESC
LIMIT 1 ", array(':username' => $user->name))->fetchAll();
var_dump($results);
Finally you can use db_query_range :
$page = 0;
$limit = 1
$results = db_query_range("SELECT address
FROM user_address
WHERE username = :username
ORDER BY time DESC",
$page * $limit,
$limit,
array(':username' => $user->name))
->fetchAll();
var_dump($results);

Try this:
$result = db_select('user_address', 'ua')
->fields('ua', array('address'))
->condition('ua.username', $user->name)
->execute()
->fetchAll();

For that we use db_select() or db_query() - first one preferable.
$query = db_select('user_address', 'u');
// Add condition and fields
$query->condition('u.username', ‘james’)
$query->fields('u’ array('u.address'));
// execute it
$result = $query->execute();
foreach ($result as $record) {
// Do something with each $record
}
For more see
https://www.drupal.org/docs/7/api/database-api/dynamic-queries/introduction-to-dynamic-queries.
update: see condition portion. Also, you can put this in a module or php executable area of your site or via drush command line.
Change the username James to match your need

$result = $result = db_select('usr_address','u')
->fields('u',array('address','uid'))
->range(0,1)
->orderby('time', 'DESC')
->condition('u.uid',$uid,'=')
->execute();
here is how it actually worked.
Thank you for your suggestions, but at the end I made it. By myself. Well, kinda ;D

Related

If Else in Order by Clause in DB API of Drupal

I have Drupal 7 site. I am using dbApi of Drupal. Now I have a query where I need to order the records.
Table Structure:-
AlbumId
Album Name
Album Created Date
Album Release Date
Now my requirement is if Album Release Date is not NULL then sort by it, else use the Album Created Date for sorting.
$query = db_select('node', 'n');
$query->condition('n.type', 'albums', '=')
->condition('status', 1) //Published.
->fields('n', array('nid'))
->orderBy('field_album_release_date_value', 'DESC')
->execute();
$result = $query->execute();
Any help highly appreciated.
Yes it is possible. You should be using addExpresion($expression).
$query = db_select('node', 'n');
$query->condition('n.type', 'albums', '=')
->condition('status', 1) //Published.
->fields('n', array('nid'));
$query->addExpression('IF(n.field_album_release_date_value is null,'
. 'n.field_album_release_date_value, n.field_album_create_date_value)'
. ' as available_date');
$query->orderBy('available_date', 'DESC');
$result = $query->execute();
Didn't test this, so you might need to tweak it, but fact is you can use addExpression to insert sql functions like min max or in your case if.

How to call an Oracle stored procedure with output parameters using doctrine?

I have been calling stored procs in Oracle using doctrine doing something like:
$sql = "CALL namespace.my_proc(".$data_source_id.", to_date('".$account_period_start."', 'YYYY-MM-DD'),'".$updated_by."')";
$stmt = $this->getDoctrine()->getManager('fdw')->getConnection()->prepare($sql);
$result = $stmt->execute();
$stmt->closeCursor();
Now the DBA team has changed one of the stored procs to accept 2 output parameters (x and y) and I am not understanding how to make that happen. Can someone please assist me with that?
Thank You
I was able to find out the info. Hope it helps someone.
$sql = "CALL namespace.my_proc(".$data_source_id.", to_date('".$account_period_start."', 'YYYY-MM-DD'),'".$updated_by."', :x, :y)";
$stmt = $this->getDoctrine()->getManager('fdw')->getConnection()->prepare($sql);
$stmt->bindParam(':x', $x, \PDO::PARAM_INPUT_OUTPUT, 32);
$stmt->bindParam(':y', $y, \PDO::PARAM_INPUT_OUTPUT, 32);
$result = $stmt->execute();
For most recent versions of doctrine:
$sql = 'call my_proc(:arg1, :arg2)';
$stmt = $em->getConnection()->prepare($sql);
$stmt->executeQuery([
':arg1' => 82,
':arg2' => 'Foo',
]);
However, for output parameters you apply the same logic for functions:
$sql = 'BEGIN :total := sum(:num1, :num2); END;';
$stmt = $em->getConnection()->prepare($sql);
$stmt->bindParam(':total', $total);
$stmt->executeQuery([
':num1' => 6,
':num2' => 7
]);
$total will store the output

Query with join not work

i am doing a query in my controller like this:
$aviso = $em->getRepository("FabricacionBundle:Aviso")->findBy(array("fecha" => $fecha));
$dql = "SELECT a FROM PedidosBundle:Articulo a WHERE a.aviso = :aviso";
if(isset($_GET['filterField']) && isset($_GET['filterValue'])){
$dql = "SELECT a FROM PedidosBundle:Articulo a JOIN ProductosBundle:Producto p WHERE a.aviso = :aviso";
$dql .= " AND " . $_GET['filterField'] . " LIKE '%" . $_GET['filterValue'] . "%'";
}
$query = $em->createQuery($dql)
->setParameter("aviso", $aviso[0]->getId());
//dump($query);die();
$paginator = $this->get('knp_paginator');
$articulos = $paginator->paginate(
$query,
$request->query->get('page', 1),
25
);
When i dont use the filter, this work, but when i use the filter i get the next error:
Cannot count query which selects two FROM components, cannot make distinction
Where is the problem? Thanks!
What SQL engine are you running ?
Note, that it's usually a very bad practice to insert anything directly from your $_GET variable into your SQL query, as this can lead to SQL injection.
Imagine, that someone sends \'; DROP TABLE something; -- in your $_GET['filterField'] - everything is gone.
From the top of my head, there is a lacking JOINing condition.

Propel multiple-parameter binding in where() clause

I'm trying to run this query on Propel 1.6 with symfony 1.4.20.
I want to bind 2 parameters onto this subquery but its not working.
$paginas = PaginaQuery::create()
->where("pagina.id not in (select id from cliente_artista where cliente_artista.cliente_id = ? and cliente_artista.culture = ?)"
,array('XXX', 'en')
)
->limit(5)
->find();
This gives me the error:
Cannot determine the column to bind to the parameter in clause
I also found this post but there is no answer (https://groups.google.com/forum/?fromgroups=#!topic/propel-users/2Ge8EsTgoBg)
Instead of using placeholders. You may use $id and $culture:
//first, get an array of the id's
//define your vars
$id = $your_id_param;
$culture = 'en';
$cliente_artistas = ClienteArtistaQuery::create()
->select('id')
->distinct()
->filterByClienteId($id)
->filterByCulture($culture)
->find();
$paginas = PaginaQuery::create()
->where("pagina.id NOT IN ?", $cliente_artistas)
->limit(5)
->find();
If this has to be done in one query, recommend using raw sql and binding the parameters into the PDO statement (but then you lose the convenience of PropelObjectCollections):
public function getResultSet($id, $culture) {
$id = $id_param;
$culture = $culture_param;
$sql = <<<ENDSQL
SELECT * from pagina
WHERE id NOT IN (SELECT distinct id
FROM cliente_artista
WHERE cliente_id = ?
AND culture = ?
)
LIMIT 5
ENDSQL;
$connection = Propel::getConnection();
$statement = $connection->prepare($sql);
$statement->bindValue(1, $id);
$statement->bindValue(2, $culture);
$statement->execute();
$resultset = $statement->fetchAll(PDO::FETCH_ASSOC); // or whatever you need
if (! count($resultset) >= 1) {
// Handle empty resultset
}
return $resultset;
}
You could also write some query methods to use propel orm query methods. Ofcourse, the propel api is beneficial reference. There are several ways to do this. I have indicated one method here which should work for you.
EDIT:
Here's an idea on doing this as one query [since useSelectQuery() requires 'relation' name], this idea assumes tables are not related but that id's are:
$paginas = PaginaQuery::create()
->addJoin(PaginaPeer::ID, ClienteArtistaPeer::CLIENTE_ID, Criteria::LEFT_JOIN)
->where("ClienteArtista.Id <> ?", $id)
->where("ClienteArtista.Culture <> ?", $culture)
->select(array('your','pagina','column','array'))
->limit(5)
->find();

symfony2 doctrine query negation of where

i wanna query for all of my categories like this:
$othercategories = $this->getDoctrine()->getRepository('Bundle:Category')->findBy(
array('language' => $language, 'active' => 1),
array('sorting' => 'ASC')
);
what i wanna do is to add another parameter to my query, i want all categories EXCEPT one with a specific id. so like:
WHERE id NOT IN ( 2 )
or
WHERE id <> 2
how can i achieve that?
You can use DQL queries like this
$em = $this->getDoctrine()->getEntityManager();
$query = $em->createQuery( 'SELECT c FROM Bundle:Category c WHERE c.language = :language AND c.active = 1 AND c.id NOT IN ( 2 ) ORDER BY c.language ASC' )
->setParameter('language', $language);
$category= $query->getResult();
Sorry I couldn't test this because I am using my phone to answer this question and I don't know your entity variables. Let me know what changes you did to make it work, it will help others.
For more info check http://symfony.com/doc/master/book/doctrine.html
You can add these queries in repository and reuse them. Refer the Cook book on http://symfony.com/doc/master/cookbook/index.html
Hope this helped.
You can use this syntax if you prefer
$repository = $this->getDoctrine()->getRepository('Bundle:Category');
$queryBuilder = $repository->createQueryBuilder();
$notInCategoryIds = array(2); // Category ids that will be excluded
$queryBuilder->select('c')
->from('Bundle:Category', 'c')
->where('c.language = :language')->setParameter('language', $language)
->andWhere('c.active = :active')->setParameter('active', 1)
->andWhere($queryBuilder->expr()->notIn('c.id', $notInCategoryIds)
->orderBy('c.sorting', 'ASC');
$results = $queryBuilder->getQuery()->getResult();
It's probably going to be more useful for other developers that prefers this syntax

Resources