tags:

views:

60

answers:

4

hi

is that possible to use WHERE like this;

$no = $_GET['no'];
$query = "SELECT * FROM `numbers` WHERE `myno` - $no = 4";
...

if not, how can i get the rows like the below example ?

EDIT: to be more clear,

$today = date("Y-m-d");
 $query = "SELECT * FROM `dates` WHERE date - $today = 7";

i want to find rows that has date field which is 7 days ago

thx

+1  A: 

You can do:

$query = "SELECT * FROM `numbers` WHERE `myno` = 4  + $no"
Juanjo Conti
but it is different from my purpose
Ahmet vardar
+2  A: 

You can do all sorts of expressions in a WHERE clause, but be careful: if you do

SELECT * FROM numbers WHERE myno - ? = 4

it'll not be able to use any indexes, whereas:

SELECT * FROM numbers WHERE myno = 4 + ?

will be able to use an index on myno.

Sharkey
i edited my question
Ahmet vardar
Yep, The same principle applies ... use the form where you're comparing the variable to a constant expression, rather than comparing a variable expression to a constant. That way indices will work.
Sharkey
+3  A: 

If the field is a date field

$query = "SELECT * FROM `numbers` WHERE `myno` = DATE_SUB(`myno`, INTERVAL 7 DAY)"

Edit: or I would prefere this

$query = "SELECT * FROM `numbers` WHERE DATEDIFF(NOW(), `myno`) = 7"

Take a look at the date functions

Terw
these looks what i am looking for, but why you prefer 2. one ?
Ahmet vardar
Just because it's less to write ^^, And a bit easies to read :)
Terw
oh i tried but it didnt work with that "WHERE date_added >= DATE_SUB(`$dt`, INTERVAL 7 DAY) ORDER BY RAND() LIMIT 0,8"
Ahmet vardar
sorry my mistake
Ahmet vardar
A: 

$weekAgo = date("Y-m-d", strtotime("-1 week"));

$query = "SELECT * FROM numbers WHERE myno = '$weekAgo';

skynorth
Why use PHP to figure out the time when MySQL have excellent functions for this?
Terw
Why use MySQL to figure out the time when PHP has excellent functions for this?1. It seems that the creator did not have a thorough understanding of MySQL, so I provided an alternative PHP answer.2. If he is gonna check multiple times, you won't need MySQL to figure out the date multiple times, it is already stored in the variable.
skynorth