I can't seem to get this to work,
Basically, what I want to do is return all the rows in which the column timestamp
is more than the variable $timestamp
, and the column hit_counter
is less than the column max_hits
.
Getting the first part to work isn't a problem, but the second part seems to be, as it still fetches rows when hit_counter
is more than max_hits
.
Here's my code:
$query = "SELECT * FROM links WHERE timestamp >= '$timestamp' AND hit_counter >= 'max_hits' AND overflow = 'NO'";
$result = mysql_query($query);
$size = mysql_num_rows($result);
That seems to return all the correct rows for timestamp
, however still continues to select rows where hit_counter
is more than max_hits
(even though it shouldn't select any at all as >=
is more than or equal to), while to inverse >=
to <=
returns no results, even though mathematically, it's valid.
I think perhaps I'm referencing max_hits
as a value incorrectly, as I don't understand why it's working in the first place?
I know my question is a little iffy, so if you need any clarification please, do ask :).
Any answers/help would be greatly appreciated!
UPDATE:
I've updated the query as per the many great answers below, (removing the '' encasing max_hits
and changing >=
to <=
but it still returns rows which are not meant to be included by the query.
Here's a pastebin to my full code: http://pastebin.com/V4vXJr1w
Here's a link to my table structure: https://docs.google.com/spreadsheet/ccc?key=0AoELUDjfbpSXdEUybkgwQmpxUnVCWlZOZnFJdzFaQmc&hl=en_GB
I think it will work if you remove quotes around 'max_hits':
$query = "SELECT * FROM links WHERE timestamp >= '".$timestamp."' AND hit_counter <= max_hits AND overflow = 'NO'";
the problem being that you are referring to the string 'max_hits' instead of the column value.
$query = "SELECT * FROM links WHERE timestamp >= '$timestamp' AND hit_counter >= 'max_hits' AND overflow = 'NO'";
If max_hits is a column, you need to lose the quotes.
$query = "SELECT * FROM links WHERE timestamp >= '$timestamp' AND hit_counter >= max_hits AND overflow = 'NO'";
Two things look wrong to me at a glance.
If you want to compare one column against another you don't want to quote the column name, mysql just see's that as comparing your hit_counter column against the string 'max_hits'.
Also perhaps I'm misunderstanding you, but I think you've got one of your greater than signs backwards. It should roughly be:
SELECT * FROM links WHERE timestamp >= '$timestamp' AND hit_counter < max_hits AND overflow = 'NO'