简体   繁体   中英

How would I use variables in my mysql query

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);

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM