Re: Why does my PDO query with named parameters return a blank result? [message #179320 is a reply to message #179319] |
Wed, 03 October 2012 21:26 |
Michael Fesser
Messages: 215 Registered: September 2010
Karma:
|
Senior Member |
|
|
.oO(tom(dot)rankin51(at)googlemail(dot)com)
> ...when I've been reading about PDO and named parameters, I always see
> examples typed as WHERE foo = :foo I struggle to see why it works in an
> example, and why it does not in one of my failed attempts? Do
> parameters have to be declared?
JFTR: There are two ways of declaring parameters in a query. One is to
give them a name like in your example above, the other is to simply
write them as a question mark: "... WHERE foo = ? ..." But besides the
different naming, the way they work is the same.
Next steps are to prepare the query and then bind the actual variables
or values to these parameters, using either bindParam() or bindValue().
So far, so good. But you have a problem or misunderstanding when dealing
with the dates. Given your examples, the column 'postdate' seems to be
of type DATETIME, which is a string type. But the way you pass
$_REQUEST['postdate'] to the DB, it will go in as a Unix timestamp,
which is an integer - this will never match!
Your parameter binding should look like:
$foo_query->bindParam (
":postdate", $_REQUEST['postdate'], PDO::PARAM_STR);
This assumes that $_REQUEST['postdate'] contains a valid date/time in
the required format.
Or you could do the comparison as Unix timestamps, but then you would
have to change your query:
....
WHERE UNIX_TIMESTAMP(postdate) = :postdate
....
and keep the binding as it is. But I would do it the first way.
> I've tried different permutations of the postdate and $mydate part, and
> I'm really not sure how I can make it say postdate > $mydate by using
> parameters. Is there an accepted way, or standard way of doing this?
Does $mydate have to be a parameter? Is it expected to change?
But what you can do anyway is to do the calculation in SQL instead of
using strtotime():
....
WHERE postdate = :postdate
AND postdate > NOW() - INTERVAL 3 MONTH
....
Micha
--
http://mfesser.de/
Fotos | Blog | Flohmarkt
|
|
|