关于MySQL WHERE的两个条件

时间:2014-02-03 08:11:24

标签: php mysql sql

我的错误是: 您的SQL语法中有错误;查看与您的MySQL服务器版本相对应的手册,以便在')和(tblforecast.Issued,如'%01-07%')附近使用正确的语法。来自tblforecast.Issued DESC'在第2行

我的代码是:

$news = "SELECT tblforecast.Fore_ID, tblforecast.Issued, 
          tblforecast.Synopsis,tblforecast.Forecaster, tblusers.FirstName,
          tblusers.LastName FROM tblforecast 
             INNER JOIN tblusers ON tblusers.UserNumber = tblforecast.forecaster 
          WHERE ((tblforecast.Valid =$type) 
              AND (tblforecast.Issued like '%$filter%' ))
           order by tblforecast.Issued DESC";

如果我在WHERE语句中只有一个条件,那就可以了。

$ type是24或12. $ filter是数字形式的“mm-dd”。

执行此操作后,将继续显示新闻:

$loadnews = mysql_query($news);

                if (!($loadnews))
                    echo mysql_error();

                while($waiting = mysql_fetch_array($loadnews))
                {
                    $NiD = $waiting['Fore_ID'];
                    $thedate = $waiting['Issued'];
                    $synop = $waiting['Synopsis'];
                    $forecaster = $waiting['FirstName']." ".$waiting['LastName'];

                    $dDate = strtotime($thedate);
                    $newDate = date('F j, Y',$dDate);
                    echo "<div class='well well-large'>
                            <p><b>$newDate</b>
                            <br><small><i>$forecaster</i></small>
                            <br>$synop</p>
                            <br><small><a href='pdetails.php?NiD=$NiD'>Read More</a></small></p>
                            </div>";                    
                }

在回应$news内容的请求时,这就是赋值语句后的内容:

SELECT tblforecast.Fore_ID, tblforecast.Issued, tblforecast.Synopsis,tblforecast.Forecaster, tblusers.FirstName, tblusers.LastName FROM tblforecast INNER JOIN tblusers ON tblusers.UserNumber = tblforecast.forecaster WHERE ((tblforecast.Valid =) AND (tblforecast.Issued like '%01-07%' ))order by tblforecast.Issued DESC

3 个答案:

答案 0 :(得分:1)

尝试

AND (tblforecast.Issued like '%' + $filter + `%' ))  
                        // or whatever is right for PHP

但更重要的是确保在尝试在sql中使用它们之前设置了变量。

答案 1 :(得分:0)

由于$news变量的输出包含:

WHERE ((tblforecast.Valid =) AND ...
                          ^^
                          ||
                      important bit

您的$type变量未设置就很简单了。

顺便说一下,当你遇到这样的错误时,你应该经常做的第一个事情是实际打印出你用于查询的字符串。理想情况下,MySQL实际上应该在错误点之前给你一些上下文,这样就更容易理解。

答案 2 :(得分:0)

鼠尾草,
 如果提到的代码与您在脚本中使用的代码完全一致,那么我没有看到任何问题。我认为这个问题可能与字符串中使用的变量有关。

我建议您使用安全变量parsing

$news = "SELECT tblforecast.Fore_ID, tblforecast.Issued, 
      tblforecast.Synopsis,tblforecast.Forecaster, tblusers.FirstName,
      tblusers.LastName FROM tblforecast 
         INNER JOIN tblusers ON tblusers.UserNumber = tblforecast.forecaster 
      WHERE ((tblforecast.Valid = '{$type}') 
          AND (tblforecast.Issued like '%{$filter}%' ))
       order by tblforecast.Issued DESC";