i try to fetch a result with this request, which works in phpayadmin:
$result_med = db_query("SELECT node.nid AS nid,
node.created AS node_created
FROM dr_wiwe_node node
LEFT JOIN dr_wiwe_content_type_classified node_data_field_classified_valid_till ON node.vid = node_data_field_classified_valid_till.vid
WHERE ((node.type in ('classified')) AND (node.status <> 0))
AND (DATE_FORMAT(STR_TO_DATE(node_data_field_classified_valid_till.field_classified_valid_till_value, '%Y-%m-%dT%T'), '%Y-%m-%d\T%H:%i:%s') >= '2010-09-16T22:34:05')
ORDER BY node_created DESC LIMIT 1");
var_dump($result_med);
while ($node = db_fetch_object($result_med)) {
//var_dump ($node);}
In the hardcoded php Version it returns nothing. If I var_dump $result_med, I am getting:
resource(552) of type (mysql result)
Where is my error?
The problem is probably caused by db_query() treating parts of your datetime formatting strings as query parameters, which it tries to replace.
So you'll need to add additional '%' characters to your existing ones to escape them, thus preventing the parameter substitution process from trying to replace them.
See the "If a query that has % in them" comment from the db_query api documentation for an example.
A cleaner/more readable solution might be to just use '%s' placeholders for the formatting strings in the query and then add the actual formatting strings as arguments to the db_query call, as suggested by Eli.
Related
This query doesn't produce an error but I'm pretty sure EXTRACT(EPOCH FROM relationships.created_at) isn't doing what it's meant to.
last_check = #user.last_check.to_i
#new_relationships = User.select('"rels_unordered".*')
.from("(#{#rels_unordered.to_sql}) AS rels_unordered")
.joins("
INNER JOIN relationships
ON rels_unordered.id = relationships.character_id
WHERE EXTRACT(EPOCH FROM relationships.created_at) > #{last_check}
GROUP BY relationships.created_at
ORDER BY relationships.created_at DESC
")
How do I check exactly what EXTRACT(EPOCH FROM relationships.created_at) is producing? The server logs don't show it, they just repeat the query. (At least the logs do show that #{last_check} correctly produces a number like 1471364015, which is why I think the problem is with the epoch code.)
I would just go to mysql and try it out:
SELECT EXTRACT(EPOCH FROM relationships.created_at) FROM relationships limit 0,1;
and see what kind of answer you get. Alter the above to specify a particular record if need be.
A larger problem may be the EPOCH parameter; I'm not sure it's valid. See the mySQL reference for EXTRACT and its parameters.
I'm having trouble generating a query in Codeigniter. The problem is
$this->db->select('user.*')
->join('user_group', 'user.group_id BETWEEN user_group.start_range AND user_group.end_range', 'left');
This code generates the following query:
SELECT `user`.* FROM (`user`) LEFT JOIN `user_group` ON `user`.`group_id` `BETWEEN` user_group.start_range AND user_group.end_range
Here, the mysql can not recognize the BETWEEN which is inside the quote character, how can I generate the query without wrapping with the quote character. Please, give me any suggestion.
I'm using codeigniter 2.2.0
You would need to either override the $_reserved_identifiers variable in the CI_DB_driver class to look like the following
var $_reserved_identifiers = array('*', 'BETWEEN'); // Identifiers that should NOT be escaped
(Note im not sure what if this reduces security)
https://github.com/bcit-ci/CodeIgniter/blob/2.2-stable/system/database/DB_driver.php#L67
The other option is to replicate the between operator using >= and <=
SELECT Batch.NumStud
FROM Batch
WHERE CourseID='$courseid'
INNER JOIN Course
ON Batch.CourseID=Course.CourseID"
an error that says mysql_fetch_array(): supplied argument is not a valid MySQL result resource in <b>F:\AppServ\www\anNoECourse.php
is shown.This code was written to feed in data to a google chart.
You put SQL in wrong order (JOIN and WHERE are switched):
SELECT Batch.NumStud
FROM Batch INNER JOIN Course
ON Batch.CourseID = Course.CourseID
WHERE Course.CourseID = '$courseid'
It seems, that your query can be simplified (check your data):
select Batch.NumStud
from Batch
where Batch.CourseID = '$courseid'
I think the error is a bit more complex. Due to the fact that your SQL is invalid, you're not getting a result set. This case is not handled correctly by your PHP code!
So in addition to correcting your SQL as the others have suggested, please make sure to handle the case where you get no results or your query results in an error correctly in your PHP code!
The second part to your solution is as follows:
$result = mysql_query(...);
if ($result)
{
while (...)
...
}
This makes sure that mysql_query actually returned a result set and not false, which it does in case of errors (due to your invalid SQL code, but also in other cases). So just fixing your SQL is not enough to make your script error proof.
But again, do no longer use the mysql_.... functions! They are deprecated.
In my Django app, I need to generate a MySQL query like this:
SELECT * FROM player WHERE (myapp_player.sport_id = 4 AND (myapp_player.last_name LIKE 'smi%'))
UNION
SELECT * FROM player WHERE (myapp_player.sport_id = 4 AND (myapp_player.first_name LIKE 'smi%'));
I can't use Q objects to OR together the __istartswith filters because the query generated by the Django ORM does not use UNION and it runs at least 40 times slower than the UNION query above. For my application, this performance is unacceptable.
So I'm trying stuff like this:
Player.objects.raw("SELECT * FROM myapp_player WHERE (sport_id = %%s AND (last_name LIKE '%%s%')) UNION SELECT * FROM sports_player WHERE (sport_id = %%s AND (first_name LIKE '%%s%'))", (sport.id, qword, sport.id, qword))
I apologize for the long one-liner, but I wanted to avoid using a triple-quoted string while trying to debug this type of issue.
When I execute or repr this queryset object, I get exceptions like this:
*** ValueError: unsupported format character ''' (0x27) at index 133
That's a single-quote in single quotes, not a triple-quote. If I get rid of the single-quotes around the LIKE clauses, then I get a similar exception about the close-paren ) character that follows the LIKE clause.
Apparently Django and MySQL disagree on the correct syntax for this query, but is there a syntax that will work for both?
Finally, I'm not sure that my %%s syntax for string interpolation is correct, either. The Django docs suggest that I should be able to use the regular %s syntax in the arguments for raw(), but several online resources suggest using %%s or ? as the placeholder for string interpolation in raw SQL.
My sincere thanks for just a little bit of clarity on this issue!
I got it to work like this:
qword = word + '%'
Player.objects.raw("SELECT * FROM myapp_player WHERE (sport_id = %s AND (last_name LIKE %s)) UNION SELECT * FROM myapp_player WHERE (sport_id = %s AND (first_name LIKE %s))", (sport.id, qword, sport.id, qword))
Besides the fact that %s seems to be the correct way to parameterize the raw query, the key here was to add the % wildcard to the LIKE clause before calling raw() and to exclude the single quotes from around the LIKE clause. Even though there are no quotes around the LIKE clause, quotes appear in the query ultimately sent to the MySQL sever.
Why does this give me an MySQL syntax error:
<cfset arguments.where = "platformUrlId='#params.platformUrlId#'">
SELECT *
FROM whatever
WHERE #arguments.where#
Order By #arguments.order#
But this works perfectly well?
<cfset arguments.where = "0=0">
SELECT *
FROM whatever
WHERE #arguments.where#
Order By #arguments.order#
It's not my param because I dumped the param next to a twin that I typed out, and they match... passing the string directly works, but setting the string in an argument then using the argument breaks it
EDIT: The error output is showing platformUrlId=''playstation3'' Coldufsion is adding '' around the argument name. How come?
In order to prevent problems when your variable contians someting like "Dexy's Midnight Runniers", CF implicitly escapes single quotes in CFQuery. You can prevent this by using preserveSingleQuotes().
However, what you are doing is definitely not a recommended practice. If you need to write this as a function, I'd do something more along the lines of passing in an array of key/value pairs, and using cfQueryParam to prevent any SQL injection.
You could probably better make use of the cfqueryparam tag like this:
<cfquery>
SELECT *
FROM tbl
WHERE #arguments.colname# = <cfqueryparam value="#arguments.platformUrlId#">
ORDER BY #arguments.order#
</cfquery>