简体   繁体   English

我将如何在MySQL查询中使用变量

[英]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. 我试图在我的mysql语句中使用变量,以便它们将根据输入而变化。 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. 但是,当我运行下面的代码时,出现错误,但是如果删除“动态” AND语句,该代码将起作用。 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. AND语句存在间距问题。

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. 对于所有* _stat变量,在字符串的开头和结尾添加一个空格,以使sql查询不会中断。

For example: 例如:

$size_stat = " AND size='$size2' ";

Also, make sure you have spaces between the "WHERE" and "HAVING" clauses. 另外,请确保在“ WHERE”和“ HAVING”子句之间有空格。

UPDATE : Also, check if the query is actually returning any results. UPDATE :另外,检查查询是否实际上返回了任何结果。

UPDATE2 : Replace the dots '.' UPDATE2 :替换点“。” in your query with spaces... 在查询中有空格...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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