Reputation: 95
I am trying to use variables in my mysql statement so they will change depending on the input. For example if the user does not enter size, that part of the statement won't show up. Sorry I am bad at explaining. But when I run the code below, I get an error, but If I remove the 'dynamic' AND statements, the code works. I just can't figure out what I am doing wrong. And ideas.
if($size2 ==''){
$size_stat = '';
}else{
$size_stat = "AND size='$size2'";
}
if($re2 ==''){
$re_stat = '';
}else{
$re_stat = "AND re='$re2'";
}
if($status2 ==''){
$status_stat = '';
}else{
$status_stat = "AND status='$status2' ";
}
$result2 = mysql_query("SELECT
lat,lng,id,re,re_num,name,city,state,zip,address,status,category,size,
( 3959 * acos( cos( radians($lat2) )
* cos( radians( lat ) )
* cos( radians( lng ) - radians($long2) )
+ sin( radians($lat2) )
* sin( radians( lat ) )
)
) AS distance
FROM
locations
WHERE
(state='PA' OR state='NY')
.$re_stat.
$size_stat.
$status_stat.
HAVING
distance < 300
ORDER BY
distance
LIMIT
0 , 50 ");
while($array = mysql_fetch_assoc($result2)){
$array_json[] = $array;
}
echo json_encode($array_json);
Upvotes: 0
Views: 74
Reputation: 23274
You have spacing issues with the AND statements.
For all your *_stat variables add a space at the beginning and at the end of the string so the sql query does not break.
For example:
$size_stat = " AND size='$size2' ";
Also, make sure you have spaces between the "WHERE" and "HAVING" clauses.
UPDATE: Also, check if the query is actually returning any results.
UPDATE2: Replace the dots '.' in your query with spaces...
Upvotes: 3