print_r($sql);
echo "\n";
print_r($sql_params);
$result = db_query($sql, $sql_params); // Error happening here
Output:
select SQL_CALC_FOUND_ROWS * from rocdocs_database_1318520218 where 1=1 order by ? ? limit ?, ?
Array
(
[0] => c5
[1] => desc
[2] => 0
[3] => 50
)
According to the documentation I can used ordered parameters by using an array and ? marks, but it seems to be erroring. Any ways to debug this? I have installed devel, but it doesn't show the query.
You can't use placeholders for anything that is "sql structure" like sort definitions, table/column names and so on. This is impossible.
If you need dynamic order by definitions, use db_select() and then orderBy(). Make sure to validate what you pass in through that.
Related
I am using Omines Symfony DataTable Bundle https://omines.github.io/datatables-bundle/#doctrine-orm to organize my event table.
I am unable to search on my "Début" and "Fin" columns which are of type Datetime Column. I'm guessing because since these are DateTime objects I'm guessing it can't find a match.
mytable
If I type "08/19/2020" it doesn't find any results for me.
Here: https://datatables.net/forums/discussion/44218/how-do-i-search-on-a-datetime-column it advises to format the date on the server side, so I tried that (of course j 've installed the doctrine extensions to be able to use date_format):
->createAdapter(ORMAdapter::class, [
'entity' => Event::class,
'query' => function (QueryBuilder $builder) use ($eventStatus) {
$builder
->select('e')
->addSelect('DATE_FORMAT(e.startDate, "%d/%m/%Y")')
->addSelect('ca')
->addSelect('ci')
->addSelect('u')
->from(Event::class, 'e')
->join('e.category', 'ca')
->join('e.city', 'ci')
->join('e.user', 'u')
->andWhere('e.status = :status')
->setParameter('status', $eventStatus)
->orderBy('e.id', 'DESC')
;
},
])
I also changed my dateStart column to TextColumn:
->add('startDate', TextColumn::class, ['label' => 'Début', 'field' => 'e.startDate', 'render' => function($value, $context) {
return sprintf(
'%s<br>
%s',
$value,
$context->getStartAt()->format('H\hi'),
);
}])
And I have this error:
Uncaught PHP Exception Doctrine \ ORM \ Query \ QueryException: "[Syntax Error] line 0, col 34: Error: Expected StateFieldPathExpression | string | InputParameter | FunctionsReturningStrings | AggregateExpression, got '"' "
I do not see where the problem is.
Thanks for your help.
It's difficult to tell from the question you are asking, but there are certain things that look problematic in your code.
First, you use a custom query, but you don't use any WHERE clause with the date.
Second, your formatting of the column is not named. The result can't be accessed since it doesn't have a name. You can name it with the keyword AS:
->addSelect('DATE_FORMAT(e.startDate, "%d/%m/%Y") AS startDateFormatted')
Third, you use joins and then you shouldn't use ORMAdapter but FetchJoinORMAdapter (this will help you solve problems with pagination when using joins).
In my opinion, you shouldn't try to format the startDate in the query, but check the documentation and use a Criteria
https://omines.github.io/datatables-bundle/#doctrine-orm
I'm getting following error when executing query .
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''0', '25'' at line 1
here is the query
$sqlData = 'SELECT * FROM users WHERE u_id_id = :UID_ID ORDER BY :ORDER_BY :ORDER_TYPE limit :START, :DATA_LENGTH';
$params = array(
":UID" => $uId,
":ORDER_BY" => $orderBy,
":ORDER_TYPE" => $orderType,
":START" => $start,
":DATA_LENGTH" => $length
);
$queryData = \registry::getDBHandler()->prepare($sqlData);
$queryData->execute($params);
var_dump($queryData->execute($params));
note
here is the var dum output of paramas
array (size=5)
':UID' => string '66' (length=2)
':ORDER_BY' => string 'id' (length=2)
':ORDER_TYPE' => string 'asc' (length=3)
':START' => string '0' (length=1)
':DATA_LENGTH' => string '25' (length=2)
Prepared statements let you bind variables to the WHERE (and I think SELECT) clauses of an SQL query. Unfortunately, they do not let you bind to the ORDER BY or LIMIT (or FROM) clauses. For that, you will need to manually append to the string.
Since those values are not being entered by the user, you should be safe from SQL injection if you just do:
$sqlData = "SELECT * FROM users WHERE u_id_id = :UID_ID ORDER BY $orderBy $orderType LIMIT $start, $length";
(Note the double quotes around the string)
And then your $params array would just be:
$params = array(":UID" => $uId);
If you are worried about SQL injection, then you can use the following to help with that:
For your ORDER BY, you can make sure that your $orderBy is in a hard-coded list of fields and reject it if it is not.
For $orderType, just simply ensure it is equal to either "asc" or "desc" (possibly ignoring case).
With $start and $length, make sure they are integers. You can also try to use intval() to convert them if need be.
If you follow these rules, then it should be safe to append these variables into your SQL query. Since $uId is part of the WHERE, you can use the prepared variable for it and that is fine.
I am trying to build a query that retrieves all the most recent and upcoming activities from database.
The entity activity has a field named date of type DateTime. So in my repository I was thinking of building something like this:
$query = $repository
->createQueryBuilder('a');
$query->orderBy( 'DATEDIFF( a.date, NOW())' , 'ASC');
$query->setMaxResults( 6 );
return $query;
Unfortunately I get the following error:
[Syntax Error] line 0, col 59: Error: Expected end of string, got '('
The Dql that is generated by my query:
SELECT a FROM MyBundle\Entity\Activity a ORDER BY DATEDIFF( a.date, NOW()) ASC
I also tried installing beberlei/DoctrineExtensions, but either it is not working or I was unable to configure it correctly.
Anyone has any suggestion?
Thanks in advance
date_diff si already implemented as Doctrine DQL statement as described here
for use as ordering statement I suggest you to use the HIDDEN select keyword as explained in this article
So your DQL is like this:
SELECT
a,
DATE_DIFF( a.date, CURRENT_TIMESTAMP() ) AS HIDDEN score
FROM MyBundle:Entity a
ORDER BY score
And add the max result on the query. Let me know if you need help to adapt as query builder statement
Hope this help
Why don't you just use
$query = $repository
->createQueryBuilder('a');
$query->orderBy( 'DATEDIFF( a.date, CURRENT_TIMESTAMP())' , 'ASC');
$query->setMaxResults( 6 );
return $query;
?
I have a query like this:
$Record = new Pod('event');
$where_clause = "DATE(enddate) >= CURDATE() AND event_type.name='Training'";
$Record->find('startdate ASC', 100, $where_clause);
It return only 1 item while I have 2 satisfy the query.
I have check with each query:
$Record = new Pod('event');
$where_clause = "DATE(enddate) >= CURDATE()";// AND
$Record->find('startdate ASC', 100, $where_clause);
And
$Record = new Pod('event');
$where_clause = "event_type.name='Training'";// AND
$Record->find('startdate ASC', 100, $where_clause);
I got 2 items on both queries.
Can you give some hints to fix this? Thanks in advance.
The code you are using is designed to work with Pods 1.X, but your query itself looks good. With Pods 2.X you would want to do the code below, which combines the pods() global function with its method find and then uses the total method to check the number of items returned.
$param = array(
"where" => "DATE(enddate) >= CURDATE() AND event_type.name='Training'",
"orbery" => "t.startdate ASC",
"limit" => "100",
);
$pod = pods( 'event', $param );
$number = $pod->total();
You know have the records in $pod and the total number in $number, which you can use to control the loop when you loop through the results in $pod. If you wanted to you could use total_found to get the number of records that would have been returned had you not limited it.
Also, have you checked that you really have two records that should be returned. It is possible that when you combine the two queries only one of them meets both conditions.
You should also check out Perry Bonwell's tutorial where he explains how to query for future events. He uses PHP, not SQL functions to handle the dates, but otherwise he has a similar approach.
I have a content types with 3 file fields, all of them can have an unlimited number of images. I need to make a view that returns the title of the content and the images name inside an array (I'm using amfphp with services). The problem is that when I add the relationship to the content field_pics fid I get as many duplicate nodes as the number of the images in the field:
EG:
[10] => stdClass Object
(
[nid] => 56
[node_title] => asd asd asd
[node_language] =>
[node_nid] => 56
)
[11] => stdClass Object
(
[nid] => 56
[node_title] => asd asd asd
[node_language] =>
[node_nid] => 56
)
This is the query:
SELECT node.nid AS nid, node.title AS node_title, node.language AS node_language, node.nid AS node_nid
FROM node node
LEFT JOIN content_field_colori node_data_field_colori ON node.vid = node_data_field_colori.vid
LEFT JOIN files files_node_data_field_colori ON node_data_field_colori.field_colori_fid = files_node_data_field_colori.fid
WHERE (node.status <> 0 OR (node.uid = ***CURRENT_USER*** AND ***CURRENT_USER*** <> 0) OR ***ADMINISTER_NODES*** = 1) AND (node.type in ('prodotto'))
ORDER BY node_nid ASC
I don't know how to fix this.
ANy help is appreciated.
Thanks
I think I understand what you're trying to do now. Unfortunately, Services's views support isn't all that great when it comes to CCK. There are a lot of different issues (e.g. one, two, three) with a lot of different patches and comments, but based on my understanding, to capture what you want is to not use relationships and to use the Node row style. If you use relationships, you get the output you're seeing, and if you use the Fields row style, the ImageField fields never load.