Query with join not work - symfony

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.

Related

Convert SQL query into Drupal 7 PHP rules

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

Select AVG of rows using Query Builder

I want to select the average of columns 'note' from a table
'noteparagraphe' where
the id_paragraphe is a parameter ($ref), I tried this query but I'm getting nothing back !
$query=$this->get('doctrine.orm.entity_manager')
->createQuery('Select avg(n.note) from ParagrapheBundle:NoteParagraphe n
WHERE n.id_paragraphe = :idModele');
$query->setParameter('idModele', $ref);
$query->execute();
$avgNote = $query->getResult();
the SQL is : SELECT AVG(note) from note_paragraphe WHERE id_paragraphe=?
Use Query builder:
$query = $this->getDoctrine()->getRepository('ParagrapheBundle:NoteParagraphe');
$avgNote = $query->createQueryBuilder('n')
->select('avg(n.note)')
->where('n.id_paragraphe = :idModele')
->setParameter('idModele', $ref);
->getQuery();
See if that works - I haven't tried it, but I think it should work.

$wpdb query not working in plugin

I'm trying to do a reviews plugin in Wordpress, and one of the thing that my client asked me to do was that a user should be able to rate only one product every 24 horas, so I have to establish a limit between rates.
And I made this function to check if the limit is reached:
function isAllowedToRate(){
global $wpdb;
$currentDate = date('Y-m-d');
$userId = get_current_user_id();
$table_name = $wpdb->prefix .'esvn_reviews';
$isAllowed = $wpdb->get_results(
"
SELECT user_id, fecha_calificacion
FROM {$table_name}
WHERE user_id = {$userId}
AND review_date = {$currentDate}
"
);
if( count( $isAllowed > 0 ) ){
return false;
}else{
return true;
}
}
But every time I try to run it, it returns false, the error that I'm getting from Wordpress is this:
<div id='error'>
<p class='wpdberror'><strong>WordPress database error:</strong> []<br />
<code>
SELECT user_id, fecha_calificacion
FROM wp_esvn_reviews
WHERE user_id = 6
AND fecha_calificacion = 2015-10-30
</code></p>
</div>
If I take the same SQL and run it directly into the database, it works like a charm, but I keep getting this error from Wordpress and the function always returns false.
You need to wrap your date in single quotes.
$isAllowed = $wpdb->get_results(
"
SELECT user_id, fecha_calificacion
FROM {$table_name}
WHERE user_id = {$userId}
AND review_date = '{$currentDate}'
"
);
Alternatively you could use $wpdb->prepare(), which I would consider better form.
$sql = <<<SQL
SELECT user_id, fecha_calificacion
FROM {$table_name}
WHERE
user_id = %d -- this is formatted as a (d)igit
AND review_date = %s -- this is formatted as a (s)tring
SQL;
$isAllowed = $wpdb->get_results($wpdb->prepare($sql, $userId, $currentDate));
I found the error (in case someone needs the information in the future), I was treating $isAllowed as an array, and it was an object, I had to add ARRAY_A to the get_results:
$isAllowed = $wpdb->get_results(
"
SELECT user_id, fecha_calificacion
FROM {$table_name}
WHERE user_id = {$userId}
AND review_date = {$currentDate}
",ARRAY_A /* output as an associative array */
);

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();

Why doesn't this WordPress $wpdb query work?

I am doing the following:
$type = 'attachment';
$images = $wpdb->get_results($wpdb->prepare('
SELECT p.*
FROM wp_%d_posts p
WHERE p.post_parent =%d
AND p.post_type = "%s"
', $blog_id, $page->ID, $type),OBJECT);
var_dump($images);
If I remove the line 'AND p.post_type = "%s"' then I get results returned, otherwise I get an empty array returned. If I run the query direct against the DB in a mysql client, I get results.
There is no error, just an empty result set. I am doing similar queries throughout my file and they are working so I'm not looking for "don't do it like that" style replies. I just need to understand why this isn't working and fix it.
PHP 5.3, MYSQL 5.1. WordPress MU 2.9.2
Do not Quote "%s". From the WordPress site, "Notice that you do not have to worry about quoting strings. Instead of passing the variables directly into the SQL query, use a %s placeholder for strings and a %d placedolder for integers."
Example:
$wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_title = %s WHERE ID = %d", $var, $id ) );

Resources