including a PHP variable into SQL query string

ThePiston

Senior member
Nov 14, 2004
861
0
76
I need to include a variable inside a string in a SQL query, but something isn't right.

This is the variable:

$curr_yr = date('Y') ;

and I need it to replace the "2015" in the following query:

$query = "SELECT COUNT(`id`)
from j17_cbsubs_subscriptions
WHERE id!=62
and id !=299
and expiry_date < '2015-12-31 23:59:58'
AND status='A'";

any help is appreciated!
 

ThePiston

Senior member
Nov 14, 2004
861
0
76
did that right after I posted when I realized that "string" was the operative word. thanks
 

ThePiston

Senior member
Nov 14, 2004
861
0
76
so this is a bad idea?

$query = "SELECT COUNT(`id`)
from j17_cbsubs_subscriptions
WHERE id!=62
and id !=299
and expiry_date < '{$curr_yr}-12-31 23:59:58'
AND status='A'";
 

Cogman

Lifer
Sep 19, 2000
10,284
138
106
so this is a bad idea?

$query = "SELECT COUNT(`id`)
from j17_cbsubs_subscriptions
WHERE id!=62
and id !=299
and expiry_date < '{$curr_yr}-12-31 23:59:58'
AND status='A'";

It depends on where curr_yr is coming from, but in general, yes. Seeing something like that makes me think "SQL injection attack" even if it isn't possible (input guaranteed to be an integer). Parameterized queries aren't much harder to write and they are always safe from injection attacks. It is just a good idea to always prefer them over string concatenation.